Spring MVC using same path on endpoints to return

2019-08-09 19:25发布

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?

2条回答
萌系小妹纸
2楼-- · 2019-08-09 20:11

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.

@RequestMapping(value="/hello" params= param1)
public returnType method(@RequestParam("param1") p) { ... }

@RequestMapping(value="/hello" params= param2)
public differentreturnType method2(@RequestParam("param2") p) { ... }

So to handle the first, request URL : http://etc.com/hello?param1=x and the second http://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--

查看更多
萌系小妹纸
3楼-- · 2019-08-09 20:18

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 to application/json for a response containing JSON and text/html for a response containing HTML.

You can then have two @RequestMapping methods like

@RequestMapping(value = "/hello", produces = "application/json")
public SomeType handleJson() {...}

@RequestMapping(value = "/hello", produces = "text/html")
public String handleHtml() {...}

Spring will determine which method to use based on the request's Accept header and the method's produces value.

查看更多
登录 后发表回答