0

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.

user1589188
  • 5,316
  • 17
  • 67
  • 130
  • 2
    You cannot, there is only 1 method that can be mapped. What is it you are trying to achieve? Please describe your usecase instead of the technical solution you are trying. – M. Deinum Feb 07 '22 at 07:47
  • @M.Deinum Thank you. Once use case is to have a catch all permission check for all endpoints with a common base path – user1589188 Feb 07 '22 at 07:57
  • That is what a `HandlerInterceptor` is for. – M. Deinum Feb 07 '22 at 08:06
  • @M.Deinum yeah ok, you think that can be an answer of my question? – user1589188 Feb 07 '22 at 08:15
  • 1
    It isn't an answer it is the answer. Create a `HandlerInterceptor` implement the `preHandle` method and if no permission return false. Or even better don't implement anything and use a proven solution like Spring Security instead of rolling your own security framework. – M. Deinum Feb 07 '22 at 08:30
  • 1
    @user1589188 `@PreAuthorize` can be added on class level to check permissions – Vlad Mamaev Feb 07 '22 at 08:33

1 Answers1

1

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.

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47