「Spring Boot」インターセプター(HandlerInterceptorAdapter)のサンプル

1.HandlerInterceptorAdapterの実装

@Component
public class AuthorInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AuthorInterceptor.class);
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("preHandle()メソッド");
        System.out.println(request.getServletPath());
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle()メソッド");
        System.out.println(request.getRequestURI());
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("afterCompletion()メソッド");
        System.out.println(request.getServletPath());
    }

}

2.WebMvcConfigurerAdapterの設定

@Configuration
public class InterceptorAdapterConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private AuthorInterceptor AuthorInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        //インターセプターの登録
        registry.addInterceptor(AuthorInterceptor).addPathPatterns("/**");
        super.addInterceptors(registry);
            }
}

3.applicationContext.xmlの設定

<mvc:interceptors>
 <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.arkgame.study.web.interceptor.AuthorInterceptor" />
 </mvc:interceptor>

 

Spring Boot

Posted by arkgame