正常情况下,springMVC的拦截器的response.sendRedirect是可以跳转的。但是,如果前端用的ajax请求,则response.sendRedirect不能正常跳转。
ajax有自己独立的请求头x-requested-with,加上springMVC有一套自己的机制处理ajax请求。
if (req.getHeader("x-requested-with")!= null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){//如果是ajax请求响应头会有x-requested-with
ServletOutputStreamout = rep.getOutputStream();
out.print("unlogin");//返回给前端页面的未登陆标识
out.flush();
out.close();
return false;
}else{
Stringindexurl=content+"/index.html";
rep.sendRedirect(indexurl);
returnfalse;
}
特别注意:springMVC默认用的是outputStream,所以在向外输出的时候,一定不能用getPrintWriter。
本文介绍了在SpringMVC中,当前端使用Ajax请求时,如何通过拦截器正确处理请求并返回数据。通常,对于Ajax请求,拦截器会检查'x-requested-with'请求头,若存在则通过ServletOutputStream返回特定信息,如'unlogin'标识,而不会使用response.sendRedirect进行页面跳转。

414

被折叠的 条评论
为什么被折叠?



