Session拦截器-spring

说明

  • 代码主要是从别的地方拷贝过来,进行修改,变成自己可用的代码,参考地方太多,找不到原文章了
  • 主要功能,实现普通请求判断是否登录以及ajax请求上来后判断Session是否过期

 java代码-拦截器写法

package com.bsd.filter;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SessionInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Exception {
		System.out.println("Interceptor:preHandle执行");

		//1.判断请求是否是ajax:  普通请求:false  ajax请求:true
		boolean is_ajax = false;
		String httpRequest = request.getHeader("x-requested-with");
		if(null != httpRequest && "XMLHttpRequest".equals(httpRequest)){
			is_ajax = true;
		}

		//普通请求:httpRequest=null   ajax请求:httpRequest=XMLHttpRequest
		System.out.println("httpRequest:"+httpRequest);

		//2.获取session信息
		Map<String,Object> admin_info = (Map<String, Object>)request.getSession().getAttribute("admin_info");

		//3.判断
		if(admin_info == null){  
			//未登录
			if(is_ajax){
				//ajax判断
				PrintWriter out = response.getWriter();  
				out.print("sessionTimeout");//session失效
				out.flush();
			}else{
				//跳转页面
				String path = request.getContextPath();
				String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

				PrintWriter out = response.getWriter();
				request.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
				StringBuffer sb = new StringBuffer("<script type=\"text/javascript\" charset=\"UTF-8\">");
				sb.append("alert(\"页面长时间未操作,请重新登录.\");");
				sb.append("window.location.href='"+basePath+"admin/login.shtml';");
				sb.append("</script>");
				out.print(sb.toString());
				out.close();
			}
			return false;
		}else{  
			//已经登录
			return true;
		}
	}

}

spring配置文件

<!-- 拦截器 -->
<mvc:interceptors>  
    <mvc:interceptor>  
        <mvc:mapping path="/**" />
        <mvc:exclude-mapping path="/admin/login.html"/>  <!-- 不拦截登录页面 -->
        <mvc:exclude-mapping path="/admin/doLogin.html"/>  <!-- 不拦截登录请求 -->
	    <mvc:exclude-mapping path="*.jsp"/>
    	<mvc:exclude-mapping path="*.html"/>
    	<mvc:exclude-mapping path="*.js"/>
    	<mvc:exclude-mapping path="*.css"/>
        <bean class="com.bsd.filter.SessionInterceptor" >  
        </bean>  
    </mvc:interceptor>  
</mvc:interceptors> 

到这里为止普通请求已经可以拦截了

ajax请求判断

$.ajax({ 
    url: "../depa/setDepaAdmin.shtml",
    data: {"d_id":d_id,"u_id":u_id},
    type:"POST",
    dataType:"json",
    success: function(data){
        if(data.state == 1){
            layer.msg(data.msg,{icon:1,time:1000});
        }else{
 	    layer.msg(data.msg,{icon:2,time:1000});
 	}
     },
    error: function (data) {
        if(data.responseText == 'sessionTimeout'){
            layer.alert('操作超时,请重新登录', {icon: 7},function(){
                window.location.href="../admin/login.shtml";
            })
        }
    }
});

猜你喜欢

转载自blog.csdn.net/u011496005/article/details/85228826