Time for some code at last! If you haven’t read my last post, please head on back here.
I’m starting things off with a very simple controller that returns HTML responses.
package com.chrisyoung.auth import org.springframework.http.MediaType import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam @Controller class LoginController { @GetMapping("/login") fun loginForm(model: Model): String { model["title"] = "Login" return "login" } @PostMapping("/login", consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE]) fun login( model: Model, @RequestParam(name = "username") username: String, @RequestParam(name = "password") password: String ): String { model["title"] = "Login" model["username"] = username; model["password"] = password; return "loggedin" } }
Annotations are extremely powerful in Spring Boot. The @Controller, @GetMapping and @PostMapping annotations are taking care of the routing and request and response handling for us. I admit that they do seem a little bit too magical, but I’ve always enjoyed a bit of magic over a bunch of boilerplate.
in the functions we can see the beautiful strictly typed parameters, including the special parameter “Model” used by the mustache templates below
The application is very simple at this point. The /login route displays a html form with fields for username and password, and when that is submitted, those values are pulled out of the form-encoded request into String-type function parameters which are just displayed on the next page. I’m not actually implementing any login logic here, just request logic. I haven’t started with REST endpoints yet, because I need a couple of actual HTML pages in my auth service for the initial login and the authorisation page.
I also need a couple of templates named to match the return values of the GET and POST mapping above
{{>_header}} <h1>Login</h1> <form method="POST" action="/login"> username: <input type="text" name="username"/> <br /> password: <input type="password" name="password"/> <br /> <input type="submit" title="login"/> </form> {{>_footer}}
/resources/templates/login.mustache
{{>_header}} <h1>Logged in</h1> <p>username {{username}}</p> <p>password {{password}}</p> {{>_footer}}
/resources/templates/loggedin.mustache
Next I’ll add a bit of logic to make it a bit more functional
Continue Reading…