Using Handler Interceptors

Interceptors are closely related to mappings because you can specify a list of interceptors that are called for each mapping. HandlerInterceptor implementations can process each request before or after the appropriate controller has processed it. You can choose to implement the HandlerInterceptor interface or extend HandlerInterceptorAdapter, which provides a default implementation for all HandlerInterceptor methods. As an example, we are going to implement a BigBrotherHandlerInterceptor that is going process each request.

Listing 17-2: BigBrotherHandlerInterceptor Implementation

image from book
package com.apress.prospring.ch17.web;      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 BigBrotherHandlerInterceptor extends HandlerInterceptorAdapter {          public void postHandle(HttpServletRequest request,          HttpServletResponse response, Object handler,          ModelAndView modelAndView) throws Exception {         // process the request     } }
image from book

The actual implementation of such an interceptor probably processes the request parameters and stores them in an audit log. To use the interceptor, we create URL mapping and interceptor bean definitions in the Spring application context file, as shown in Listing 17-3.

Listing 17-3: HandlerMapping and HandlerInterceptor Definitions

image from book
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ¿ "">      <beans>     <bean bold">bigBrotherHandlerInterceptor"          />          <bean bold">publicUrlMapping"          >         <property name="interceptors">             <list>                 <ref local="bigBrotherHandlerInterceptor"/>             </list>         </property>         <property name="mappings">             <props>                 <prop key="/index.html">indexController</prop>                 <prop key="/product/index.html">productController</prop>                 <prop key="/product/view.html">productController</prop>                 <prop key="/product/edit.html">productFormController</prop>             </props>         </property>     </bean> </beans>
image from book

You can specify as many HandlerMapping and HandlerInterceptor beans as you like, provided that the actual mappings do not collide with each other.

Now that you know how Spring maps the URLs to controllers, let's take a look at the pivotal component of the Spring MVC architecture—the controllers.

Pro Spring
Pro Spring
ISBN: 1590594614
EAN: 2147483647
Year: 2006
Pages: 189

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: