<mvc:interceptors><mvc:interceptor><mvc:mapping path="/to_form1.action" /> <!-- 需拦截的地址 --><!-- 拦截所有请求 --> <mvc:mapping path="/**" /> <!-- 需要拦截的一级请求--> <mvc:mapping path="/*.do" /> <mvc:mapping path="/*.action" /> <mvc:mapping path="/*.jsp" /> <!-- 需要拦截的二级请求 --> <mvc:mapping path="/*/*.do" /> <mvc:mapping path="/*/*.action" /> <mvc:mapping path="/*/*.jsp" /> <!-- 需排除拦截的请求 --> <mvc:exclude-mapping path="/login.action"/> <mvc:exclude-mapping path="/front/login.jsp"/> <!-- 自定义拦截器类 --><bean class="util.UserInterceptor" /> </mvc:interceptor></mvc:interceptors>
在springmvc的配置文件中添加(注意:不是spring的配置文件)
package util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import pojo.User; public class UserInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { User sessionUser = null; sessionUser = (User) request.getSession().getAttribute("user"); if ( sessionUser == null ) { response.sendRedirect(request.getContextPath() + "/login.action"); return false; }else{ return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
自定义拦截器类