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

slhcrj9b  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(458)

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

<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获取变量的值,但它说varible电子邮件不存在。我知道这一点,所以任何帮助将不胜感激。
我想说的是:

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

hfsqlsce1#

你想把表格寄过去 POST 方法,但您的控制器仅为 @GetMapping . 更改或添加 @PostMapping ,然后添加 @RequestBody Model model (如果等级 Model 描述你的形式)和所有应该工作。
如果您刚开始编程,请阅读有关http的内容:https://www.w3schools.com/tags/ref_httpmethods.asp 在这种情况下 @RequestBody : https://www.baeldung.com/spring-request-response-body

相关问题