1.mvc.xml
<!-- 自定义拦截链配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/supplier/*"/>
<mvc:mapping path="/goods/*"/>
<mvc:mapping path="/contact/*"/>
<bean class="com.young4j.controller.UserInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:interceptors>
<!-- 局部拦截器 -->
<mvc:interceptor>
<mvc:exclude-mapping path="/user_login" />
<mvc:exclude-mapping path="/user_logout" />
<mvc:mapping path="/**" />
<bean class="com.young4j.interceptor.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
登录拦截器
public class LoginInterceptor implements HandlerInterceptor { //日志
protected Logger log = Logger.getLogger(getClass()); public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handle) throws Exception { //创建session
HttpSession session =request.getSession(); //无需登录,允许访问的地址
String[] allowUrls =new String[]{"/toLogin","/login"}; //获取请求地址
String url =request.getRequestURL().toString(); //获得session中的用户
UserToken user =(UserToken) session.getAttribute("userToken"); for (String strUrl : allowUrls) {
if(url.contains(strUrl))
{
return true;
}
} if(user ==null)
{
throw new UnLoginException("您尚未登录!"); }
//重定向
//response.sendRedirect(request.getContextPath()+"/toLogin"); return true; } @Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub } @Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub } }
设置session
HttpSession session=event.getSession;
session.setMaxInactiveInterval(30*60);//以秒为单位