I have following three REST API methods :
@RequestMapping(value = "/{name1}", method = RequestMethod.GET)
public Object retrieve(@PathVariable String name1) throws UnsupportedEncodingException {
return configService.getConfig("frontend", name1);
}
@RequestMapping(value = "/{name1}/{name2}", method = RequestMethod.GET)
public Object retrieve(@PathVariable String name1, @PathVariable String name2) throws UnsupportedEncodingException {
return configService.getConfig("frontend", name1, name2);
}
@RequestMapping(value = "/{name1}/{name2}/{name3}", method = RequestMethod.GET)
public Object retrieve(@PathVariable String name1, @PathVariable String name2, @PathVariable String name3) {
return configService.getConfig("frontend", name1, name2,name3);
}
getConfig method is configured to accept multiple parameters like:
public Object getConfig(String... names) {
My Question is : is it possible to achieve the above RequestMapping using only one method/RequestMapping ?
Thanks.
Simple approach
You can use /**
in your mapping to grab any URL and then extract all parameters from the mapping path. Spring has a constant which allows you to fetch the path from the HTTP request. You just have to remove the unnecessary part of the mapping and split the rest to get the list of parameters.
import org.springframework.web.servlet.HandlerMapping;
@RestController
@RequestMapping("/somePath")
public class SomeController {
@RequestMapping(value = "/**", method = RequestMethod.GET)
public Object retrieve(HttpServletRequest request) {
String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
String[] names = path.substring("/somePath/".length()).split("/");
return configService.getConfig("frontend", names);
}
}
Better approach
However, path variables should be rather used for identifying resources in your application and not as a parameters to a given resource. In that case, it is advised to stick with simple request parameters.
http://yourapp.com/somePath?name=value1&name=value2
You mapping handler would look much more simple:
@RequestMapping(method = RequestMethod.GET)
public Object retrieve(@RequestParam("name") String[] names) {
return configService.getConfig("frontend", names);
}
You should probably use @RequestParam instead and method POST in order to achieve what you want.
@RequestMapping(name = "/hi", method = RequestMethod.POST)
@ResponseBody
public String test(@RequestParam("test") String[] test){
return "result";
}
And then you post like that:
So your array of Strings will contain both values
Also in REST a path corresponds to a resource, so you should ask yourself "what is the resource i am exposing ?". It would probably be something like /config/frontend and then you specify your options through request params and/or HTTP verbs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With