By kswaughs | Tuesday, February 9, 2016

Spring mvc interceptor with annonations

Interceptors are used to intercept the web requests from the user and they are executed before and after processing the requests.

Spring MVC allows us to intercept through handler interceptors. The custom interceptor have to extend the HandlerInterceptorAdapter class, and override below methods :

1. preHandle() is called before the handler execution and returns a boolean value. If it is true then continue the handler execution chain otherwise stop the execution chain and return it.

2. postHandle() is called after the handler execution, allow manipulate the ModelAndView object before render it to JSP page.

In this example, I am printing the request URI before processing the request and printing the modelMap of ModelAndView object after processing the request.

Step 1 : Create an interceptor class that extends HandlerInterceptorAdapter.

TransactionInterceptor
package com.kswaughs.interceptor;

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 TransactionInterceptor extends HandlerInterceptorAdapter {
  
    @Override
    public boolean preHandle(
        HttpServletRequest request,
        HttpServletResponse response, 
        Object handler) throws Exception {
  
        System.out.println("Before Request Processing : request.getRequestURI(): "
            + request.getRequestURI());
  
        return true;
    }
 
    @Override
    public void postHandle(
        HttpServletRequest request,
        HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {

        System.out.println("After Request Processing : modelAndView.getModelMap(): "
            + modelAndView.getModelMap());
    }
}

Step 2 : Map the interceptors to the required urls.

My appname is spring_app and I have two URIs
/phones
/phones/details
But I applied interceptor to only '/phones/details'. 
SpringWebConfig

package com.kswaughs.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.kswaughs.interceptor.TransactionInterceptor;

@EnableWebMvc 
@Configuration
@ComponentScan({ "com.kswaughs.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
 
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/jsps/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
  
        registry.addInterceptor(new TransactionInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/phones");
    }
}

Output in server console

Before Request Processing : request.getRequestURI(): /spring_app/phones/details
After Request Processing : modelAndView.getModelMap(){phone=Phone [id=2, name=Nokia Lumia, price=12,000], org.springframework.validation.BindingResult.phone=org.springframework.validation.BeanPropertyBindingResult: 0 errors}

Recommend this on


No comments:

Post a Comment