1.需求:在部分需要判断用户是否存在的情况下访问一些页面,如果用户不是登录状态则需要先登录。
package com.iflysse.bbs.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class AuthorInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); if(session.getAttribute("user") == null){ response.sendRedirect(request.getContextPath() + "/login"); return false; } return true; } }
在spring-serlvet.xml中添加:
<!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor>
<!--访问的路径在/person后的进行拦截--> <mvc:mapping path="/person/**" /> <bean class="com.iflysse.bbs.interceptor.AuthorInterceptor" /> </mvc:interceptor> </mvc:interceptors>
原文:http://www.cnblogs.com/wyl9527/p/6492003.html