Springboot实现Session拦截器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq3399013670/article/details/87858125

springboot实现session拦截器供参考:

//session拦截器
@Component("sessionInterceptor")
public class SessionInterceptor extends HandlerInterceptorAdapter{

   // 忽略的URL地址
	private static final String[] IGNORE_URI = {"/login","/logintest"};
	
    @Override  
    public boolean preHandle(HttpServletRequest request,
    		HttpServletResponse response, Object handler) throws Exception 
    {   
    	SessionInfo session = (SessionInfo) request.getSession().getAttribute("session");
    	
    	String requestURI = request.getRequestURI();
    	String contextPath = request.getContextPath();
    	contextPath = contextPath+"/";

    	for (int i = 0; i < IGNORE_URI.length; i++) {
           // 忽略的url地址
			if (requestURI.contains(IGNORE_URI[i]) || requestURI.equals(contextPath)) {
				return true;
			} 
		}
    	//如果session为空则提示未登录
    	if(!requestURI.contains(IGNORE_URI[i])&& null == session) {
    		String requestType = request.getHeader("X-Requested-With"); 
    		if(!BaseUtil.stringIsNull(requestType)){
    			if("XMLHttpRequest".equals(requestType)) {
    				throw new GenericException("session为空");
    			}
    		}
    		request.getRequestDispatcher("/WEB-INF/views/login/login.jsp").forward(request, response);
    	}
		return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq3399013670/article/details/87858125