SpringMVC自定义拦截器详解

HandlerInterceptor接口的代码如下:
package org.springframework.web.servlet;    
import Javax.servlet.http.HttpServletRequest;   
import Javax.servlet.http.HttpServletResponse;   
public interface HandlerInterceptor {    
     // preHandle()方法在业务处理器处理请求之前被调用   
     boolean preHandle(HttpServletRequest request,HttpServletResponse response,  Object handler) throws Exception;    
     // postHandle()方法在业务处理器处理请求之后被调用   
     void postHandle(    
             HttpServletRequest request, HttpServletResponse  response, Object    
             handler, ModelAndView modelAndView)   
             throws Exception;    
     // afterCompletion()方法在DispatcherServlet完全处理完请求后被调用   
     void afterCompletion(    
             HttpServletRequest request, HttpServletResponse  response, Object    
             handler, Exception ex)   
             throws Exception;    
   
 }   

下面对代码中的三个方法进行解释。

preHandle():这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求request进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回true;如果程序员决定不需要再调用其他的组件去处理请求,则返回false。

postHandle():这个方法在业务处理器处理完请求后,但是DispatcherServlet向客户端返回请求前被调用,在该方法中对用户请求request进行处理。

afterCompletion():这个方法在DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。

下面通过一个例子来说明如何使用SpringMVC框架的拦截器。

现在要编写一个拦截器,拦截所有不在工作时间的请求,把这些请求转发到一个特定的静态页面,而不对它们的请求进行处理。

首先编写TimeInterceptor.Java,代码如下:
package com.yjde.web.interceptor;  
  
import java.util.Calendar;  
  
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 TimeInterceptor extends HandlerInterceptorAdapter {  
    // 继承HandlerInterceptorAdapter类  
  
    private int openingTime; // openingTime 属性指定上班时间  
    private int closingTime; // closingTime属性指定下班时间  
    private String outsideOfficeHoursPage;// outsideOfficeHoursPage属性指定错误提示页面的URL  
  
    // 重写 preHandle()方法,在业务处理器处理请求之前对该请求进行拦截处理  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
        Calendar cal = Calendar.getInstance();  
        int hour = cal.get(Calendar.HOUR_OF_DAY); // 获取当前时间  
        if (openingTime <= hour && hour < closingTime) { // 判断当前是否处于工作时间段内  
            return true;  
        } else {  
            response.sendRedirect(outsideOfficeHoursPage); // 返回提示页面  
            return false;  
        }  
    }  
  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object o, ModelAndView mav)  
            throws Exception {  
        System.out.println("postHandle");  
    }  
  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object o, Exception excptn)  
            throws Exception {  
        System.out.println("afterCompletion");  
    }  
  
    public int getOpeningTime() {  
        return openingTime;  
    }  
  
    public void setOpeningTime(int openingTime) {  
        this.openingTime = openingTime;  
    }  
  
    public int getClosingTime() {  
        return closingTime;  
    }  
  
    public void setClosingTime(int closingTime) {  
        this.closingTime = closingTime;  
    }  
  
    public String getOutsideOfficeHoursPage() {  
        return outsideOfficeHoursPage;  
    }  
  
    public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {  
        this.outsideOfficeHoursPage = outsideOfficeHoursPage;  
    }  
  
}  

可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在 openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个页面,返回 false,这样该请求就不会被处理。

下面是在dispatcher-servlet.xml中对拦截器进行的配置,代码如下:
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/aop   
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <!--  
        使Spring支持自动检测组件,如注解的Controller  
    -->  
    <context:component-scan base-package="com.yjde.web.controller" />  
  
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />  
    <mvc:interceptors>  
        <mvc:interceptor>  
            <!--设置拦截的路径-->  
            <mvc:mapping path="/login1.htm" />  
            <mvc:mapping path="/login2.htm" />  
            <bean class="com.yjde.web.interceptor.TimeInterceptor">  
                <!--openingTime 属性指定上班时间-->  
                <property name="openingTime">  
                    <value>12</value>  
                </property>  
                <!--closingTime属性指定下班时间-->  
                <property name="closingTime">  
                    <value>14</value>  
                </property>  
                <!--outsideOfficeHoursPage属性指定提示页面的URL-->  
                <property name="outsideOfficeHoursPage">  
                    <value>http://localhost:8080/SpringMVCInterceptor/jsp/outsideOfficeHours.jsp  
                    </value>  
                </property>  
            </bean>  
        </mvc:interceptor>  
    </mvc:interceptors>  
    <bean id="messageSource"  
        class="org.springframework.context.support.ResourceBundleMessageSource"  
        p:basename="message">  
    </bean>  
</beans>

    可以看出,上面代码用bean</span>标签去定义TimeInterceptor,令其id为officeHoursInterceptor,并给它的3个 属性赋值。具体的大家可以运行一下项目看看。
    说 明:控制反转是Spring</span>框架的核心思想,即用一个接口去定义一些操作,在接口的实现类中去重写这些操作,然后在Spring的配置 文件中去把该接口的实现类注入到应有框架中,这样就可以通过调用接口去调用接口的实现类。此次讲的拦截器就体现了这种思想,即实现 HandlerInterceptorAdapter接口,重写preHandle()方法并在配置文件中实现TimeInterceptor的注入。这 
样当框架调用HandlerInterceptorAdapter时,就可以调用到TimeInterceptor类的preHandle()方法。

猜你喜欢

转载自674544686-qq-com.iteye.com/blog/2248565