package com.filter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.bz.common.util.ConstantUtil;
/**
* 用户登录拦截器
* @author Wangbt
*
*/
public class LoginInterceptor implements HandlerInterceptor {
// 不拦截的地址
private static final String[] IGNORE_URL = { "/login.action" };
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean flag = false;
String url = request.getRequestURI().toString();
for (String s : IGNORE_URL) {
if (url.contains(s)) {
flag = true;
break;
}
}
if (!flag) {
HttpSession session = request.getSession(true);
Object obj = session.getAttribute("userInfo");
if (obj == null || "".equals(obj.toString())) {// 未登录
if (request.getHeader("x-requested-with") != null
&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {// 如果是ajax请求,响应头会有x-requested-with
response.setHeader("sessionStatus", "timeout");// 设置session超时状态
}else{
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
} else {
flag = true;
}
}
return flag;
}
@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
}
}
springmvc-servlet.xml中配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 不拦截地址 **代表任意字符串标识 -->
<mvc:exclude-mapping path="/interface/**/*.action"/>
<bean id="loginInterceptor" class="com.filter.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>