如何使用 thymeleaf 获取输入用户名的值?

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

如何获取登录表单中输入的用户名的值?

我的登录表单是:

<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>

我的控制器是:

@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";
}
}

我试图使用@RequestParam 来获取变量的值,但它说变量电子邮件不存在。我知道这一点,所以任何帮助将不胜感激。

这是我想要做的:

@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";
}

您正在尝试通过 POST 方法发送表单,但您的控制器仅为 @GetMapping 定义。更改或添加 @PostMapping,然后添加 @RequestBody Model model(如果 class Model 描述您的表单),一切都应该有效。

如果您刚开始编程,请阅读有关 HTTP 的内容:https://www.w3schools.com/tags/ref_httpmethods.asp and in this case about @RequestBody: https://www.baeldung.com/spring-request-response-body