我正在使用Spring MVC,我需要对服务器进行异步调用并检查用户的凭据。如果它匹配,那么我将重定向到另一页。
MyController.java
@RequestMapping("performingLogin.htm")
public ModelAndView performingLogin(@RequestParam String username, @RequestParam String password)
{
//boolean value which decides whether its a valid user
myService.performingLogin(username, password);
//Currently returning the new model to be opened irrespective of valid user
ModelAndView model = new ModelAndView("newpage");
return model;
}
MainView.jsp
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doAjaxPost() {
$.ajax({
url : "dologin.htm",
data : {
username: $('#username').val(),
password: $('#password').val()
},
success : function(responseTxt,statusTxt,xhr) {
/* Opening new page */
window.location.href="newpage.htm";
}
});
}
我需要知道如何在JSP端验证用户,以便我可以发出凭据不正确的警告。
答案 0 :(得分:2)
检查@ResponseBody注释
public @ResponseBody String performingLogin(@RequestParam String username, @RequestParam String password)
{
}
答案 1 :(得分:1)
在您的代码中,您完全忽略了返回的视图并在成功时执行了js重定向。只要您这样做,返回ModelAndView
或@ResponseBody
注释值之间就没有真正的区别。
您可能希望返回401 Unauthorized
http错误,然后在您的javascript中检查。
有多种方法可以做到。
一种方法是创建一个异常并使用spring注释对其进行注释,然后抛出它。
有些事情:
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class AuthenticationException extends RuntimeException {
private static final long serialVersionUID = 23949237498237948234l;
}
将您的请求映射更改为:
@RequestMapping("performingLogin.htm")
public ModelAndView performingLogin(@RequestParam String username, @RequestParam String password)
{
//boolean value which decides whether its a valid user
myService.performingLogin(username, password);
if (authenticationWentWrong) {
throw new AuthenticationException();
}
//Currently returning the new model to be opened irrespective of valid user
ModelAndView model = new ModelAndView("newpage");
return model;
}
然后你的js代码:
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doAjaxPost() {
$.ajax({
url : "dologin.htm",
data : {
username: $('#username').val(),
password: $('#password').val()
},
success : function(responseTxt,statusTxt,xhr) {
/* Opening new page */
window.location.href="newpage.htm";
},
statusCode : {
401: function(jqXHR, textStatus, errorThrown) {
//handle the authentication error here
}
}
});
}
答案 2 :(得分:0)
此外,您可能想尝试HTTPResponseEntity,我认为它经常被忽视,但可以让您获得更大的控制权 - 对于spring 3.2.的新测试包非常有用