Search code examples
springspring-mvcspring-data-jpathymeleafdao

How to get the value of the input username with thymeleaf?


How can I get the value of the input username in a login form?

My login form is:

<form th:action="@{/login}" method="post">
                <div class="form-group">
                    <input type="text" name="username" id="username"
                           class="form-control" th:placeholder="Email" autofocus required/>
                </div>

                <div class="form-group">
                    <input type="password" name="password" id="password"
                           class="form-control" th:placeholder="Password" required/>
                </div>

                <input type="submit" class="btn btn-lg btn-primary btn-block"
                       th:value="Login"/>

            </form>

And my controller is :

@Controller
public class LoginController {

@GetMapping("/login")
public String login(@RequestParam(value = "error", required = false) String error, Model model, 
Principal principal) {

    if (principal != null) {
        return "redirect:/ccursos";
    }

    if (error != null) {
        model.addAttribute("msg",
                "Error al iniciar sesión: Nombre de usuario o contraseña incorrecta, por favor vuelva 
  a intentarlo!");
    }

    return "login";
}

@GetMapping("/logout")
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login";
}
}

I was trying to use the @RequestParam to get the value of the variable, but it says the varibale Email doesn't exist. I'm knew to this so any help would be appreciated.

Here is what I'm trying to to:

@GetMapping("/login")
public String login(@RequestParam(value = "error", required = false) String error,@RequestParam("Email") String email,
        Model model, Principal principal) {
    if (principal != null) {
        return "redirect:/ppeliculas";
    }
    if (error != null) {
        model.addAttribute("msg",
                "Error al iniciar sesión: Nombre de usuario o contraseña incorrecta, por favor vuelva 
   a intentarlo!");
    }
    return "login";
}

Solution

  • You are trying to send form by POST method but your controller is defined only for @GetMapping. Change or add @PostMapping, then add @RequestBody Model model (if class Model describe your form) and all should works.

    If you are starting with programing read something about HTTP: https://www.w3schools.com/tags/ref_httpmethods.asp and in this case about @RequestBody: https://www.baeldung.com/spring-request-response-body