JoBins採用企業サイト JoBinsエージェントサイト

アカウントをお持ちの方はこちら 採用企業ログイン
エージェントログイン


background

HandlerInterceptors in Spring MVC

Jan 9, 2018

1. Introduction

In this article we will focus on implementing the Spring MVC HandlerInterceptor.


2. Spring MVC Handler

Handler Interceptors are generally used to perform actions when the view is rendered or certain request is executed.
Interceptors that are handling the mappings should implement the HandlerInterceptor interface.
This interface consists of following methods:

 

handler-interceptor

prehandle()- It is called before the handler is executed. i.e before the view is rendered

postHandle()- called after the handler is executed i.e while the view is being rendered.

afterCompletion()- called after the complete request is finished and the view has been rendered.

 

These three methods provide flexibility to do all kinds of pre- and post-processing.
Here's a simple implementation of a Basic HandlerInterceptor


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse, 
    Object o, ModelAndView modelAndView) throws Exception {

         //Your Code        
            modelAndView.addObject("foo","bar"); 

    }

    @Override
     public void afterCompletion( HttpServletRequest httpServletRequest,  
      HttpServletResponse httpServletResponse,Object o, Exception e) throws Exception {

    }
}

This aricle is an quick introduction on intercepting HTTP requests using Spring MVC Handler Interceptor.