当我尝试访问loginCheck
方法时,我有error,请勿重定向我以查看CONTACTS
视图或将我重定向到LOGIN
视图,对于两者,我添加了一个if句子。
我不知道此错误的原因,仅适用于POST类型的方法请求。
我添加了日志,看看当我请求这些方法时会发生什么,我得到了这个:Logs
转到网址“localhost/8080/”
时,我会重定向到LOGIN
视图,如图中所示,当我按下按钮登录LOGIN
视图时,出现错误。这是我的控制器的代码:
@Controller
public class LoginController {
private static final Log LOG = LogFactory.getLog(LoginController.class);
@GetMapping("/")
public String redirectToLogin() {
LOG.info("METHOD: redirectToLogin()");
return "redirect:/login";
}
@GetMapping("/login")
public String showLoginForm(Model model,
@RequestParam(name="error", required=false) String error,
@RequestParam(name="logout", required=false) String logout) {
LOG.info("METHOD: showLoginForm() -- PARAMS: error"+ error + ", logout:" + logout);
model.addAttribute("error", error);
model.addAttribute("logout", logout);
model.addAttribute("userCredentials", new UserCredential());
LOG.info("Returning to login view");
return "login";
}
@PostMapping("/logincheck")
public String loginCheck(@ModelAttribute(name="userCredentials") UserCredential userCredential) {
LOG.info("METHOD: loginCheck() -- PARAMS: " + userCredential.toString());
if(userCredential.getUsername().equals("user") && userCredential.getPassword().equals("user")) {
LOG.info("Returning to contacts view");
return "contacts";
}
LOG.info("Redirect to login?error");
return "redirect:/login?error";
}
}
这是LOGIN视图代码:
登入
<div class="container">
<form class="form-signin" action="#" th:action="@{/logincheck}" th:object="${userCredentials}" metod="post">
<h2 class="form-signin-heading">Sign in</h2>
<label for="inputEmail" class="sr-only">Username</label>
<input type="text" id="inputUsername" class="form-control" placeholder="Username" th:field="*{username}"/>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" th:field="*{password}"/>
<div th:if="${error != null}" class="alert alert-danger" role="alert">Invalid username or password</div>
<button class="btn btn-lg btn-primary btn-black" type="submit">
<span class="glyphicon glyphicon-log-in" aria-hiden="true"></span>Sign in
</button>
</form>
</div> <!-- /container -->
答案 0 :(得分:0)
当您在浏览器上访问 loginCheck url时,它会向应用程序服务器发送GET请求。但是你的控制器期待一个POST请求,因此错误。您可以修改控制器以处理GET或使用其他方式(例如AJAX)以POST方式登录。