Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot controller path extend another path

We have an application with path pattern like this:

/{language}/{subsystem}/blah/blah

the language and subsystem variable will do some common logic and apply to all 100+ controllers, i wanna ask instead of repeating this common logic 100 times in each controller, is there a way to define a centralized controller like

/{language}

which is to handle the language logic and another centralized controller like

and /{subsystem}

which is to handle the subsystem logic and all other controller kinda of 'extend' from these controllers ? Hope i describe it clearly. many thanks and happy weekend:)

like image 766
Frank Avatar asked Nov 07 '22 11:11

Frank


1 Answers

You could think about writing a custom Interceptor for your application. This interceptor could fetch the language and subsystem parts from your URL path and invoke your common logic in a central place.

There are a few pitfalls to this approach that you should balance carefully:

  1. it's very implicit - people might miss that your interceptor is in place and could be in for a surprise
  2. it'll apply for all incoming requests - if you want it to skip certain requests, you have to implement this logic within the interceptor

Personally, I'd take another approach and go for a combination of @RequestMapping and @PathVariable annotations on every controller method to capture language and subsystem and put the common logic into a helper method:

@GetMapping("/{language}/{subsystem}/something")
public String doSomething(@PathVariable Language language, @PathVariable Subsystem subsystem) {
    LanguageSubsystemHelper.doSomething(language, subsystem);
    // ...
}

Reduce the repetition to a minimum by providing a helper that's available for all controller methods. The benefits of this approach are:

  1. you have granular control when to use or not use the common logic
  2. it's explicit
  3. you can automatically validate language and subsystem by binding the path variables to an enum
like image 193
Ham Vocke Avatar answered Nov 12 '22 19:11

Ham Vocke