Spring Boot Adding Http Request Interceptors

What is the correct way to add HttpRequest hooks to a spring boot application? What I want to do is log requests and responses for each HTTP request.

Spring boot documentation does not cover this topic at all. ( http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/ )

I found some web samples on how to do the same with older versions of spring, but they work with applicationcontext.xml. Please, help.

+78
java spring spring-boot spring-mvc
Jun 26 '15 at 10:19
source share
6 answers

Since you are using Spring Boot, I suggest that you would rather rely on Spring autoconfiguration where possible. To add additional custom configuration, such as your interceptors, simply provide the configuration or WebMvcConfigurerAdapter component.

Here is an example config class:

 @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired HandlerInterceptor yourInjectedInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(...) ... registry.addInterceptor(getYourInterceptor()); registry.addInterceptor(yourInjectedInterceptor); // next two should be avoid -- tightly coupled and not very testable registry.addInterceptor(new YourInterceptor()); registry.addInterceptor(new HandlerInterceptor() { ... }); } } 

NOTE: do not annotate this with @EnableWebMvc if you want to keep Spring Boots automatically configured for mvc .

+123
Jun 26 '15 at 22:51
source

WebMvcConfigurerAdapter will deprecate using Spring 5. From Javadoc :

@deprecated with 5.0 {@link WebMvcConfigurer} has default methods (made possible using the Java 8 baseline) and can be implemented directly without using this adapter.

As stated above, you should run WebMvcConfigurer and override the addInterceptors method.

 @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyCustomInterceptor()); } } 
+56
Aug 09 '17 at 8:09 on
source

To add an interceptor to the spring boot application do the following

  • Create an interceptor class

     public class MyCustomInterceptor implements HandlerInterceptor{ //unimplemented methods comes here. Define the following method so that it //will handle the request before it is passed to the controller. @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response){ //your custom logic here. return true; } } 
  • Define a configuration class

     @Configuration public class MyConfig extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**"); } } 
  • Here it is. Now all your requests will go through the logic defined in the preHandle () method of MyCustomInterceptor.

+22
Feb 08 '17 at 12:24
source

You might also consider using the open source SpringSandwich library, which allows you to directly annotate in your Spring Boot controllers which hooks are used, much like you annotate your URL routes.

Thus, there are no typo-prone lines floating around - the SpringSandwich method and class annotations easily survive refactoring and make it clear what is applied and where. (Disclosure: I am the author).

http://springsandwich.com/

+7
Nov 30 '16 at 16:32
source

I had the same problem as for WebMvcConfigurerAdapter. When I searched for examples, I almost did not find any implemented code. Here is a snippet of working code.

create a class that extends HandlerInterceptorAdapter

 import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import me.rajnarayanan.datatest.DataTestApplication; @Component public class EmployeeInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String x = request.getMethod(); logger.info(x + "intercepted"); return true; } } 

then run the WebMvcConfigurer interface

 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired EmployeeInterceptor employeeInterceptor ; @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee"); } } 
+7
03 Oct '17 at 17:03
source

Since all the answers to this use the now obsolete abstract WebMvcConfigurer adapter instead of WebMvcInterface (as @sebdooe already noted), here is a working minimal example for a SpringBoot (2.1.4) application with an interceptor:

Minimal.java:

 @SpringBootApplication public class Minimal { public static void main(String[] args) { SpringApplication.run(Minimal.class, args); } } 

MinimalController.java:

 @RestController @RequestMapping("/") public class Controller { @GetMapping("/") @ResponseBody public ResponseEntity<String> getMinimal() { System.out.println("MINIMAL: GETMINIMAL()"); return new ResponseEntity<String>("returnstring", HttpStatus.OK); } } 

Config.java:

 @Configuration public class Config implements WebMvcConfigurer { //@Autowired //MinimalInterceptor minimalInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MinimalInterceptor()); } } 

MinimalInterceptor.java:

 public class MinimalInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception { System.out.println("MINIMAL: INTERCEPTOR PREHANDLE CALLED"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MINIMAL: INTERCEPTOR POSTHANDLE CALLED"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println("MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED"); } } 

works as advertised

The output will give you something like:

 > Task :Minimal.main() . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _' | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.4.RELEASE) 2019-04-29 11:53:47.560 INFO 4593 --- [ main] io.minimal.Minimal : Starting Minimal on y with PID 4593 (/x/y/z/spring-minimal/build/classes/java/main started by x in /x/y/z/spring-minimal) 2019-04-29 11:53:47.563 INFO 4593 --- [ main] io.minimal.Minimal : No active profile set, falling back to default profiles: default 2019-04-29 11:53:48.745 INFO 4593 --- [ main] osbwembedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2019-04-29 11:53:48.780 INFO 4593 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-04-29 11:53:48.781 INFO 4593 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17] 2019-04-29 11:53:48.892 INFO 4593 --- [ main] oaccC[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-04-29 11:53:48.893 INFO 4593 --- [ main] osweb.context.ContextLoader : Root WebApplicationContext: initialization completed in 1269 ms 2019-04-29 11:53:49.130 INFO 4593 --- [ main] ossconcurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-04-29 11:53:49.375 INFO 4593 --- [ main] osbwembedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-04-29 11:53:49.380 INFO 4593 --- [ main] io.minimal.Minimal : Started Minimal in 2.525 seconds (JVM running for 2.9) 2019-04-29 11:54:01.267 INFO 4593 --- [nio-8080-exec-1] oaccC[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2019-04-29 11:54:01.267 INFO 4593 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2019-04-29 11:54:01.286 INFO 4593 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet : Completed initialization in 19 ms MINIMAL: INTERCEPTOR PREHANDLE CALLED MINIMAL: GETMINIMAL() MINIMAL: INTERCEPTOR POSTHANDLE CALLED MINIMAL: INTERCEPTOR AFTERCOMPLETION CALLED 
0
Apr 29 '19 at 10:27
source



All Articles