import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.test.entity.Employee;
/**
* Spring 拦截器
*
* @author jhwen
*
*/
public class SessionInterceptor extends HandlerInterceptorAdapter {
private final Logger logger = Logger.getLogger(SessionInterceptor.class);
/**
* 在业务处理器处理请求之前被调用
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception{
//要排除拦截的请求
String[] ignoreRegexs = new String[]{"login.do","checkCode.do"};
//获取客户端请求URI
String requestURI = request.getRequestURI();
//获取客户端请求
if(null!=requestURI && !"".equals(requestURI)){
//不同的工程,substring(int paramInt1,int paramInt2)的paramInt1不同
requestURI = requestURI.substring(8, requestURI.length());
}
for(int i=0; i<ignoreRegexs.length; i++){
String ignoreRegex = ignoreRegexs[i];
/**
* 如果是login.do 和 checkCode.do, 则不做拦截
*/
if(ignoreRegex.equals(requestURI)){
return true;
}
}
/**
* 如果不是login.do(登录) 和 checkCode.do(检验验证码), 则做拦截,
* 并且,判断是否已经登录
*/
Employee emp = (Employee)request.getSession().getAttribute("emp");
/**
* 如果未登录,则不允许操作;
* 如果已经登录,则允许做其他的操作.
*/
if(null == emp){
return false;
}else{
return true;
}
}
}
Spring 的核心配置文件 applicationContext.xml:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<bean class="com.test.common.core.interceptor.SessionInterceptor" />
</list>
</property>
</bean>