Spring MVC 4的Interceptor攔截器與Struts2的攔截器相似,其主要目的是對全部的URL請求進行攔截處理,處理某些規則的請求,如權限驗證,判斷用戶是否登錄等。
在Spring MVC 4中使用攔截器,必須先在Spring.xml中配置使用攔截器,配置的方法有兩種:一種是傳統的bean方式配置,另一種是使用 http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 定義的<mvc:interceptors>。具體實現代碼以下:
方案一:使用bean配置interceptors攔截器
web
<beans> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> <property name="interceptors"> <list> <ref bean="loginInterceptor"/> </list> </property> </bean> <bean id="loginInterceptor" class="com.favccxx.favblog.interceptor.LoginInterceptor"> </bean> <beans> |
<mvc:interceptors> <mvc:interceptor> <!-- 默認全部的請求都進行攔截 --> <mvc:mapping path="/*"/> <bean class="com.favccxx.favblog.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> |
public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub System.out.println("------" + System.nanoTime()); return true; } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { FavUser favUser = (FavUser) (request.getSession()).getAttribute(SysConstants.USER_SESSION_KEY); if (favUser == null) { modelAndView.setViewName("redirect:/login"); } }} |