【Java.Spring.MVC】使用HandlerInterceptor拦截请求

Spring的handler mapping机制提供了handler interceptors,可以用来为特定的请求添加特定的功能,如,检测资金额等。

handler mapping的拦截器必须实现HandlerInterceptor的接口。该接口定义了三个方法:

  • preHandler() - 在实际的handler被执行前被调用
  • postHandler() - 在handler被执行后被调用
  • afterCompletion() - 当request处理完成后被调用

preHandler()方法返回一个布尔值。可以使用该方法继续或者中断执行链。当返回true,继续执行链;如果返回false,则停止后续的执行。

Interceptor使用interceptors属性进行配置,该属性为HandlerMapping类的属性。

例如:

<beans>
    <bean id="handlerMapping"
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="officeHoursInterceptor"/>
            </list>
        </property>
    </bean>

    <bean id="officeHoursInterceptor"
            class="samples.TimeBasedAccessInterceptor">
        <property name="openingTime" value="9"/>
        <property name="closingTime" value="18"/>
    </bean>
<beans>
package samples;

public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {

    private int openingTime;
    private int closingTime;

    public void setOpeningTime(int openingTime) {
        this.openingTime = openingTime;
    }

    public void setClosingTime(int closingTime) {
        this.closingTime = closingTime;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(HOUR_OF_DAY);
        if (openingTime <= hour && hour < closingTime) {
            return true;
        }
        response.sendRedirect("http://host.com/outsideOfficeHours.html");
        return false;
    }
}

该handler请求的任何request都会被TimeBasedAccessInterceptor所中断。

使用是配置HandlerInterceptorAdaptor类作为中断器的基类(HandlerInterceptor接口的实现类)。




  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值