Issue
I have got a spring mvc controller which has many methods.
In all the methods I start the path by /api
followed by the actual word.
Currently I have to manually type /api/request1
/api/request2
and so on. Is there a way to only mention my request name and /api
gets appended automatically?
Controller:
package com.json.host;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Test {
@GetMapping(value="/api/host")
public String returnText() {
return "hello";
}
}
Solution
You can add @RequestMapping("/api")
on class level and omit it on method level then.
So something like this should do the trick:
@RestController
@RequestMapping("/api")
public class Test {
@GetMapping(value="/host")
public String returnText() {
return "hello";
}
}
Documented also in javadoc:
Supported at the type level as well as at the method level! When used at the type level, all method-level mappings inherit this primary mapping, narrowing it for a specific handler method.
Answered By - Seb
Answer Checked By - Pedro (JavaFixing Volunteer)