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接口的实现类)。