Spring MVC在端点上使用相同的路径返回不同的内容? [英] Spring MVC using same path on endpoints to return different content?

查看:224
本文介绍了Spring MVC在端点上使用相同的路径返回不同的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用一个非常基本的hello world终结点作为示例

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";
 }

如果我有此端点,并且希望能够转到/hello并检索helloworld视图.

If I have this endpoint and I want to be able to go to /hello and retrieve the helloworld view.

如果我传入诸如content-type之类的特定请求参数,是否可以使用SAME /hello路径将模型检索为json?

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?

推荐答案

我不确定我理解你的意思.

I'm not sure I understand what you mean.

如果您希望能够发送请求到/hello并获得具有不同内容类型的两个不同响应,那么可以.

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将方法标识为请求处理程序,但它还提供了一些选项来限制应使用处理程序的时间.

@RequestMapping identifies a method as being a request handler, but it also provides options for restricting when the handler should be used.

在这种情况下,应该在HTTP请求中使用Accept标头,对于包含JSON的响应,将其设置为application/json,对于包含HTML的响应,将其设置为text/html.

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.

然后您可以拥有两个@RequestMapping方法,例如

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将根据请求的Accept标头和方法的produces值来确定使用哪种方法.

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

这篇关于Spring MVC在端点上使用相同的路径返回不同的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆