SessionInterceptor.java 2.53 KB
package com.bjivt.web.interceptor;

import java.util.List;

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

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

import com.google.common.collect.Lists;

/**
 * 权限中的session拦截器,用来检测某个session是否存在,不存在就跳转到登录页面
 * 
 * lyd
 */
public class SessionInterceptor implements HandlerInterceptor {
	private List<String> ignoreList = Lists.newArrayList();
	private String sessionName;
	private String loginUrl;

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public List<String> getIgnoreList() {
		return ignoreList;
	}

	public void setIgnoreList(List<String> ignoreList) {
		this.ignoreList = ignoreList;
	}

	public String getSessionName() {
		return sessionName;
	}

	public void setSessionName(String sessionName) {
		this.sessionName = sessionName;
	}

	/**
	 * 释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	/**
	 * 在生成视图前,就是通过拦截器反向返回给客户端时执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在运行业务代码前,就是用户提交数据到服务器时执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		AntPathMatcher matcher = new AntPathMatcher();
		if (matcher.match(request.getContextPath() + loginUrl, url)) {
			return true;
		}
		if (isIgnore(request.getContextPath(),url)) {
			return true;
		}
		HttpSession session = request.getSession();
		if (session.getAttribute(sessionName) != null) {
			return true;
		}
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		response.sendRedirect(basePath + loginUrl);
		return false;
	}

	private boolean isIgnore(String contextPath,String url) {
		AntPathMatcher matcher = new AntPathMatcher();
		for (String matchurl : ignoreList) {
			if (matcher.match(contextPath+matchurl, url)) {
				return true;
			}
		}
		return false;
	}

}