简体   繁体   中英

How to ignore base path url in Spring MVC?

I want to make several controllers for such paths with a common prefix v1.0 :

  • mysite.com/v1.0/users
  • mysite.com/v1.0/addresses
  • mysite.com/v1.0/phones

However, also I want to keep controllers paths without this prefix, for example:

  • mysite.com/monitoring/ping

The prefix v1.0 can be changed in the future. So, I don't want to duplicate this prefix for each controller not to change it everywhere iteratively whenever the prefix is changed.

I can write this property in application.properties to add a prefix:

  • spring.data.rest.basePath=/api/v1

But in this case I will not be able to get requests on the addresses without this prefix.

The question is how to organize such a service?

You could use

@RestController
@RequestMapping("/v1")
public class SomeController {

on classlevel. Then all @RequestMapping in this Class will be accesible with the prefix "/v1". On a sidenote I would suggest not to use "." in your urls.

If you don´t want to use the String in each Controller the only option that I can think of is the following. I tried it out and it seems to be working fine for me.

@RestController
@RequestMapping("/${your.custom.property.in.application.properties}")
public class SomeController { 

your.custom.property.in.application.properties = 1

--> The URL http://localhost:8080/1/test sends me a repsonse. The URL mapping was successful. Debugger stops in breakpoints in this Controller

I think, you can keep all controller methods with similar prefix like mysite.com/v1.0/.../... in same class and at class level you can use @RequestMapping(/v1.0) . for example

@RequestMapping(/v1.0)
class Class1
{
    @GetMapping(/users)
    public String method1()
    {....}
    .
    .
    .

    @PostMapping(/addresses)
    public String method2()
    {....}

    @GetMapping(/phones)
    public String method3()
    {....}
}

and if you don't want to keep controller methods within the same prefix then you can create another class and don't annotate it at the class level. Only annotate all controller methods with different prefixes.

class Class2
{
    @GetMapping(/monitoring/ping)
    public String method1()
    {....}
    .
    .
    .
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM