初生牛犊之spring(五)

spring拦截器

自定义的拦截器必须实现org.springframework.web.servlet.HandlerInterceptor接口

1.编写拦截器

实现HandlerInterceptor接口的各个实现类
package cn.HandlerInterceptor;

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 AddHIA extends HandlerInterceptorAdapter{
    /**
     * 整个请求处理后调用
     * @param request
     * @param response
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object object,Exception ex)throws Exception{
        System.out.println("整个请求处理后调用");            
    }
    /**
     * 执行后调用
     * @param request
     * @param response
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView)throws Exception{
        System.out.println("开始后执行");            
    }
    
    /**
     * 执行前调用
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throws Exception{
        System.out.println("开始前执行");
        return true;        
    }
}

2.修改配置文件,即可使用拦截器

修改dispatcherServlet-Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
   <!-- 定义映射 -->
   <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
       <!-- 定义拦截器 -->
       <property name="interceptors">
          <list>
            <ref bean="AddHIA"/>
          </list>
       </property>
       <property name="mappings">
          <props>
             <prop key="helloWorld.do">helloWorldAction</prop>
          </props>
       </property>
   </bean>
   <!-- 定义视图 -->
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
           <value>org.springframework.web.servlet.view.InternalResourceView</value>
        </property>
        <property name="prefix">
           <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
           <value>.jsp</value>
        </property>
   </bean>
   <!-- 定义控制器 -->
   <bean id="helloWorldAction" class="cn.Spring.MVC.HelloWorldAction">
        <property name="helloWorld">
           <value>Helloworld,您好spring</value>
        </property>
        <property name="viewPage">
           <value>hello</value>
        </property>
   </bean>
   <bean id="AddHIA" class="cn.HandlerInterceptor.AddHIA"></bean>
</beans>

 

posted @ 2013-04-08 15:09  深海巨坑  阅读(126)  评论(0编辑  收藏  举报