Spring学习(2)Spring mvc拦截器

来源:互联网 发布:复杂的sql查询语句 编辑:程序博客网 时间:2024/05/29 10:58


一、Spring提供的拦截器接口和拦截适配器

Spring中提供了拦截器接口HandlerInterceptor和拦截适配器HandlerInterceptorAdapter,可以通过实现接口或者继承自适配器来自定义拦截器。

 

二、拦截器中的方法

以HandlerInterceptor接口为例,有三个方法。

Ø  preHandler方法在action之前调用。(权限控制)

Ø  postHandler方法在生成视图之前调用。

Ø  afterCompletion方法最后执行。(资源释放、异常日志处理)

 

三、自定义拦截器

public classSecurityInteceptor implements HandlerInterceptor {

   @Override

   public booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Objecthandler)throwsException {

        System.out.println("preHandle start..........");

        return true;

   }

   @Override

   public voidpostHandle(HttpServletRequest request, HttpServletResponse response, Objecthandler,

            ModelAndView modelAndView) throws Exception {

        System.out.println("postHandle start..........");

   }

   @Override

   public voidafterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex)

            throws Exception {

        System.out.println("afterCompletion start.........");

   }

}

 

四、拦截器的配置

Spring拦截器的配置有三种方案:

Ø  拦截所有url

    <mvc:interceptors>

        <beanclass="com.sohu.spaces.grap.inteceptor.SecurityInteceptor"/>

    </mvc:interceptors>

 

Ø  根据url匹配拦截

    <mvc:interceptors>

        <mvc:interceptor>

           <mvc:mappingpath="/user/*"/>

           <beanclass="com.sohu.spaces.grap.inteceptor.SecurityInteceptor"/>

        </mvc:interceptor>

        <mvc:interceptor>

           <mvc:mappingpath="/sitemap/*"/>

           <beanclass="com.sohu.spaces.grap.inteceptor.SecurityInteceptor"/>

        </mvc:interceptor>

    </mvc:interceptors>

 

Ø  在HandlerMapping上拦截

    <beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">      

         <propertyname="interceptors">      

            <list>      

                <beanclass="com.sohu.spaces.grap.inteceptor.SecurityInteceptor"></bean>     

            </list>      

         </property>      

    </bean>