当对portlet的某请求最终发送到Controller的前后,可以做一些预处理和后处理,这些处理可以用拦截器来实现,他们往往处理与真实的Controller业务无关的事情,比如安全性检查,日志。
要为某Controller应用一组拦截器可以用以下的步骤:
(1)自定义拦截器的类实现,这些拦截器类必须实现HandlerInterceptor接口
(2) 在Spring 的bean配置文件中定义这些拦截器的类的实例,并且将这些实例添加到
HandlerMapping的bean实例的interceptors属性中。
- <bean id="loggingInterceptor" class="..."/>
- <bean id="securityInterceptor" class="..."/>
- <bean id="portletModeHandlerMapping"
- class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">
- ...
- <property name="interceptors">
- <list>
- <ref bean="loggingInterceptor"/>
- <ref bean="securityInterceptor"/>
- </list>
- </property>
- </bean>
(3) 每一个拦截器最终都实现了HandlerInterceptor接口,因此都有以下几个方法:
- public abstract interface HandlerInterceptor
- {
- public abstract boolean preHandleAction(ActionRequest paramActionRequest, ActionResponse paramActionResponse, Object paramObject)
- throws Exception;
- public abstract void afterActionCompletion(ActionRequest paramActionRequest, ActionResponse paramActionResponse, Object paramObject, Exception paramException)
- throws Exception;
- public abstract boolean preHandleRender(RenderRequest paramRenderRequest, RenderResponse paramRenderResponse, Object paramObject)
- throws Exception;
- public abstract void postHandleRender(RenderRequest paramRenderRequest, RenderResponse paramRenderResponse, Object paramObject, ModelAndView paramModelAndView)
- throws Exception;
- public abstract void afterRenderCompletion(RenderRequest paramRenderRequest, RenderResponse paramRenderResponse, Object paramObject, Exception paramException)
- throws Exception;
- public abstract boolean preHandleResource(ResourceRequest paramResourceRequest, ResourceResponse paramResourceResponse, Object paramObject)
- throws Exception;
- public abstract void postHandleResource(ResourceRequest paramResourceRequest, ResourceResponse paramResourceResponse, Object paramObject, ModelAndView paramModelAndView)
- throws Exception;
- public abstract void afterResourceCompletion(ResourceRequest paramResourceRequest, ResourceResponse paramResourceResponse, Object paramObject, Exception paramException)
- throws Exception;
- public abstract boolean preHandleEvent(EventRequest paramEventRequest, EventResponse paramEventResponse, Object paramObject)
- throws Exception;
- public abstract void afterEventCompletion(EventRequest paramEventRequest, EventResponse paramEventResponse, Object paramObject, Exception paramException)
- throws Exception;
- }
在Handler(Controller)执行之前,所有拦截器的preHandleXXX()方法会被依次调用,在Handler(Controller)执行之后,所有拦截器的postHandleXXX() 方法会被依次调用。最终afterXXXCompletion()方法会被调用来执行一些清理工作。
转载于:https://blog.51cto.com/supercharles888/845170