我希望我的 ajax 调用命中Spring mvc controller
并返回jsp view
我为此编写了以下代码
$(document).on("click","#loginSubmit",function(event){
var userName=$("#userName").val();
var pwd=$("#password").val();
var url = contextPath+"/authenticate";
$.ajax({
url : url,
type:"get",
data:"&userName="+userName+"&pwd="+pwd,
contentType:'application/json; charset=utf-8',
async: false,
success:function(response)
{
console.log(response);
}
});
});
这是我的控制器
@RequestMapping(value="/authenticate")
@ResponseBody
public ModelAndView dashboard(@RequestParam("userName") String username,@RequestParam("pwd") String pwd) throws IOException
{
boolean res=false;
try {
res=service.authenticate(username,pwd);
}
catch (Exception e) {
e.printStackTrace();
}
if(res =true)
{
return new ModelAndView("dashboard");
}
else {
return new ModelAndView("login");
}
}
当我点击提交时,它返回 JSP 代码而不是 JSP 视图。
怎么做,我的代码不正确吗?
这里有一些东西混在一起。 首先,您使用的是 @ResponseBody,它将返回调用/login 的正文。
其次,我知道你想使用ajax是因为身份验证验证,但如果身份验证成功,为什么不在javascript中调用/dashboard。
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@ResponseBody
public AuthenticateDto dashboard(@RequestParam("userName") String username,@RequestParam("pwd") String pwd) throws IOException
{
return new AuthenticateDto(service.authenticate(username,pwd));
}
Ajax 调用总是期望来自控制器的一些响应,因此这个"ajax 调用命中 Spring mvc 控制器并返回 jsp 视图"是不可能的。
您可以做的是在从控制器获得成功响应后,您可以重定向到一个控制器方法URL,该URL将返回JSP页面。
success:function(response)
{
window.location.href = "/urlToDashboard";
}
在控制器中:
@RequestMapping(value="urlToDashboard")
public String dashboardPage()
{
return "dashboard"; // return dashboard.jsp page
}