原因:
ajax请求默认就是不支持重定向的,因为它是局部刷新,不重新加载页面。
在拦截器中通过获取session(我的用户信息是存在session中)判断用户的登陆状态,没有登陆重定向到登陆页面。
请求路径获取:
1. request.getScheme() 返回当前链接使用的协议;
2. request.getServerName() 获取网站的域名;
3. request.getServerPort() 获取的服务器的请求端口;
4. request.getContextPath()获取当前的系统路径;
后端代码:
- import java.io.IOException;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.apache.log4j.Logger;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- public class LoginInterceptor implements HandlerInterceptor{
-
- private static Logger logger = Logger.getLogger(LoginInterceptor.class);
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- response.setHeader("Access-Control-Allow-Origin", "http://localhost"); // 允许跨域请求
- response.setHeader("Access-Control-Allow-Credentials", "true");
- HttpSession session = request.getSession();
- Object userId = session.getAttribute("userId");
- if(userId == null){
- logger.info("用户未登录");
- requestDirect(request, response);
- return false;
- }else{
- return true;
- }
- }
-
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
- ModelAndView modelAndView) throws Exception {
-
- }
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
- throws Exception {
-
- }
-
- public void requestDirect(HttpServletRequest request, HttpServletResponse response) throws IOException{
- //获取当前请求的路径
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+request.getContextPath();
- //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求
- if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
- //前端需要判断是否是重定向
- response.setHeader("REDIRECT", "REDIRECT");
- //需要重定向的路径
- response.setHeader("CONTENTPATH", basePath+"/login.html");
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- }else{
- response.sendRedirect(basePath + "/login.html");
- }
- }
-
- }
前端代码:
下面的代码请放在全局的js中 (用于初始化ajax请求,让它结束之后运行completer后面的函数)
- var jqxhr;
- //设置ajax请求完成后运行的函数,
- $.ajaxSetup({
- complete:function(){
- if("REDIRECT" == jqxhr.getResponseHeader("REDIRECT")){ //若HEADER中含有REDIRECT说明后端想重定向,
- var win = window;
- while(win != win.top){
- win = win.top;
- }
- win.location.href = jqxhr.getResponseHeader("CONTENTPATH");//将后端重定向的地址取出来,使用win.location.href去实现重定向的要求
- }
- }
- });
$.ajaxSetup()方法的详解链接