Spring mvc 学习(三 拦截器的使用)

如果想在CONTROLER执行的前后做一些拦截的动作,可以继承HandlerInterceptorAdapter。然后重写他中的三个方法。

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoggerInterceptor extends HandlerInterceptorAdapter {

 @Override
 public void afterCompletion(HttpServletRequest request,
   HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  // TODO Auto-generated method stub
  System.out.println("afterHandle");
 }

 @Override
 public void postHandle(HttpServletRequest request,
   HttpServletResponse response, Object handler,
   ModelAndView modelAndView) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("postHandle");
 }

 @Override
 public boolean preHandle(HttpServletRequest request,
   HttpServletResponse response, Object handler) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("preHandle");
  return true;
 }
}

preHandler会在处理请求之前来执行,传回的BOOLEAN决定是否让CONTROLER来处理请求,如果为FALSE,那么就不接着处理请求,postHandler会在CONTROLER处理完请求之后被执行,afterCompletion也会在VIEW完成后被执行。定义了拦截器以后,配置在配置文件中。

 

<bean id="log" class="com.action.LoggerInterceptor"></bean>
 
 <bean id="urlHandleMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="interceptors">
   <list>
    <ref bean="log"/>
   </list>
  </property>
  <property name="mappings">
   <props>
    <prop key="/hello.do">helloController</prop>
   </props>
  </property>
 </bean>

 

注意,使用的UrlHandlerMapping是SimpleUrlHandlerMapping

你可能感兴趣的:(spring,mvc,Web,bean,servlet)