[JAVA] [Spring Boot] I investigated how to implement post-processing of the received request.

I will be in charge of the project that realizes API ⇔ API cooperation processing with external services. Make a note of the various research / implementation of the title.

environment

Requirements

The person in charge on the external service side said the following.

In response to the above, when I was designing the API on this side, I thought about the following.

If you do the above, I wonder if it will meet the demands of the external service first. Even here, it's easier to return what you return first. The code image is below.

SampleController.java


@RestController
public class SampleController() {
    //Accepting requests from external services
    @RequestMapping(value = "/sample")
    public String sample(@Validated SampleForm form) {
        //Minimal processing to return a response
        return "";
    }

    //Post-processing(Image: If you read this article, it will not be implemented like this)
    private void after() {
        //Processing required other than returning a response
    }
}

Realization method

After investigating, it seems that it can be realized by HandlerInterceptor # afterCompletion (). I referred to the following article. Understanding how to implement common request processing on Spring MVC (+ Spring Boot)

HandlerInterceptor is an interface that also has methods for purposes other than post-processing, This time, I want to implement only the post-processing individually, so Prepare a class that inherits HandlerInterceptorAdapter, which is an implementation class of HandlerInterceptor. Also, from the perspective of post-processing, HandlerInterceptor # postHandle () is also a candidate, This is excluded because it does not meet our requirements as it will not be called when an exception occurs. HandlerInterceptor # afterCompletion () is called whether it ends normally or an exception occurs.

SampleInterceptor.java


public class SampleInterceptor extends HandlerInterceptorAdapter {
    //At the end of normal/AfterCompletion because I want to implement only post-processing regardless of abnormal termination()Only override
    @override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
      //Post-processing implementation
    }
}

Next, our requirement is to apply post-processing only to requests for / sample in the above code image. This can be addressed with the following implementation, which is also mentioned in the article above.

WebMvcConfig.java


@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    //I have to register the bean
    @Bean
    public SampleInterceptor sampleInterceptor() {
        return new SampleInterceptor();
    }
    @Bean
    public HogeInterceptor hogeInterceptor() {
        return new HogeInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sampleInterceptor())
                .addPathPatterns("/sample"); //The target is specified here
        //If you want to specify multiple Interceptors, write them side by side. You can also chain and specify multiple paths
        registry.addInterceptor(hogeInterceptor())
                .addPathPatterns("/hoge").addPathPatterns("/huga")
        //If you specify the same path in different Interceptors, both afterCompletions()Is executed
        //It has not been investigated how the execution order is decided
                .addPathPatterns("/sample");
                
    }
}

With the above, the required processing has been realized. If you don't specify a target with ʻaddPathPatterns`, all Controllers seem to be subject to post-processing.

The actual code is not limited to the sample code above, but there are a few more. That's all I want to write down.

Recommended Posts

[Spring Boot] I investigated how to implement post-processing of the received request.
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I want to understand the flow of Spring processing request parameters
I want to control the default error message of Spring Boot
How to read Body of Request multiple times with Spring Boot + Spring Security
The story of raising Spring Boot 1.5 series to 2.1 series
[Spring Boot] How to refer to the property file
03. I sent a request from Spring Boot to the zip code search API
How to set environment variables in the properties file of Spring boot application
How to use CommandLineRunner in Spring Batch of Spring Boot
How to boot by environment with Spring Boot of Maven
The story of raising Spring Boot from 1.5 series to 2.1 series part2
About the function of Spring Boot due to different versions
[Swift] I tried to implement the function of the vending machine
How to set Spring Boot + PostgreSQL
How to use ModelMapper (Spring boot)
Let's find out how to receive in Request Body with REST API of Spring Boot
What I did in the migration from Spring Boot 1.4 series to 2.0 series
What I did in the migration from Spring Boot 1.5 series to 2.0 series
I examined the concept of the process to understand how Docker works
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
I investigated the internal processing of Retrofit
How to determine the number of parallels
[Swift] How to implement the countdown function
I tried to implement the Iterator pattern
How to sort the List of SelectItem
How to split Spring Boot message file
How to apply thymeleaf changes to the browser immediately with #Spring Boot + maven
Procedure to make the value of the property file visible in Spring Boot
How to access Socket directly with the TCP function of Spring Integration
I used Docker to solidify the template to be developed with spring boot.
How to implement the email authentication function at the time of user registration
How to find the cause of the Ruby error
I want to output the day of the week
Customize how to divide the contents of Recyclerview
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
[Swift] How to implement the LINE login function
How to make Spring Boot Docker Image smaller
How to check the latest version of io.spring.platform to describe in pom.xml of Spring (STS)
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
[swift5] How to implement the Twitter share function
How to use Spring Boot session attributes (@SessionAttributes)
I want to var_dump the contents of the intent
Let's check the feel of Spring Boot + Swagger 2.0
How to implement the breadcrumb function using gretel
Try to implement login function with Spring Boot
How to get today's day of the week
[For beginners] How to implement the delete function
Output of how to use the slice method
How to add a classpath in Spring Boot
[Swift] How to implement the fade-in / out function
How to bind to property file in Spring Boot
How to display the result of form input
I wanted to gradle spring boot with multi-project
I tried to clone a web application full of bugs with Spring Boot
I want to see the contents of Request without saying four or five
[Java] How to get the authority of the folder
Spring Boot --How to set session timeout time
I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.