Reputation: 194
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";
}
}
Upvotes: 0
Views: 212
Reputation: 61
You need to add @RequestMapping(value = "/api") at the class level. it's appended to method level requests automatically.
@RestController
@RequestMapping(value = "/api")
public class Test {
@GetMapping(value="/request1")
public String returnText() {
return "hello";
}
@GetMapping(value="/request2")
public String returnText2() {
return "hello2";
}
}
Upvotes: 0
Reputation: 1861
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.
Upvotes: 3
Reputation: 8634
You can add a @RequestMapping("/api")
at class level and in your methods mapping have only the rest of the url.
package com.json.host;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api")
public class Test {
@GetMapping(value="/host")
public String returnText() {
return "hello";
}
}
Upvotes: 1