I'm going to use a very basic hello world endpoint as an example
@RequestMapping("/hello")
public String hello(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "helloworld";
}
If I have this endpoint and I want to be able to go to /hello and retrieve the helloworld
view.
Is it possible for me to use the SAME /hello
path to retrieve model as json if I pass in a specific request param like content-type?
You could try passing in a parameter using the
RequestMapping
params option. This does require modifying the URL, but the mapping is still the same and a mapped method without a params tag could be added as a default.So to handle the first, request URL :
http://etc.com/hello?param1=x
and the secondhttp://etc.com/hello?param2=y
.Params section of
@RequestMapping
docs: http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#params--I'm not sure I understand what you mean.
If you mean that you want to be able to send a request to
/hello
and get two different responses, with different content types, yes, you can do that.@RequestMapping
identifies a method as being a request handler, but it also provides options for restricting when the handler should be used.In this case, you should use the
Accept
header in your HTTP request and set it toapplication/json
for a response containing JSON andtext/html
for a response containing HTML.You can then have two
@RequestMapping
methods likeSpring will determine which method to use based on the request's
Accept
header and the method'sproduces
value.