Say I have a @RestController like below:
@RestController
@RequestMapping("/1st")
public class MyController {
@GetMapping("/2nd/aaa")
public void getAaa() {
...
}
@GetMapping("/2nd/bbb")
public void getBbb() {
...
}
}
I want to add methods to catch all requests with the base path "/1st" and "/1st/2nd" in between and then continue to the correct endpoint. I tried adding:
@GetMapping("/**")
public void doThisFirst() {
...
}
But that didn't work, a request to "/1st/2nd/bbb" still only landed on the method getBbb() only. Please help, thank you.
CodePudding user response:
I want to add methods to catch all requests with the base path "/1st" and "/1st/2nd" in between and then continue to the correct endpoint. I tried adding:
@GetMapping("/**") public void doThisFirst() { ... }
Probably you want to execute some extra code (code in doThisFirst) before you execute the respecting code that each endpoint have.
There are 2 solutions here.
A) You define an aspect with @Before that will be executed before the code that your final endpoint has. Here is some example code
B) You define an interceptor which will be executed only before those 2 endpoints. Check here some previous SO answer.
Either the interceptor or the aspect should contain the code that you have in doThisFirst() and you want to execute before you reach the actual endpoint.
In every case this starting code should not be inside a controller, so you can remove the @GetMapping("/**") from the controller.
CodePudding user response:
The functionality you are looking for is called Filter. Filters catch all the incoming requests, do some actions, and pass it on into correct endpoint. They also catch outgoing info after endpoint sends the response. Here is an article that explains how to write and configure your filters: How to Define a Spring Boot Filter?
