java 如何在 Spring MVC 中映射 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13570243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map JSON object in Spring MVC?
提问by AndreaNobili
I am studying the Spring MVS Showcase downloadable from di STS dashboard. I am studying how Spring maps the request and I am having some problem to understand the following thing:
我正在研究可从 di STS 仪表板下载的 Spring MVS Showcase。我正在研究 Spring 如何映射请求,但在理解以下内容时遇到了一些问题:
I have this form with a submit button:
我有一个带有提交按钮的表单:
<li>
<form id="byConsumes" class="readJsonForm" action="<c:url value="/mapping/consumes" />" method="post">
<input id="byConsumesSubmit" type="submit" value="By consumes" />
</form>
</li>
When I click on the submit button a Jquery function that creates a JSON object is passed by the HTTP Post Request, this is the code of the JQuery function:
当我单击提交按钮时,HTTP Post 请求会传递一个创建 JSON 对象的 Jquery 函数,这是 JQuery 函数的代码:
$("form.readJsonForm").submit(function() {
var form = $(this); // Variabile che si riferisce all'elemento nel DOM che ha scatenato l'evento click (il form)
var button = form.children(":first"); // Seleziona il bottone submit
var data = form.hasClass("invalid") ? // OPERATORE CONDIZIONALE: il form ha classe "invalid" ?
"{ \"foo\": \"bar\" }" : // SI: foo = bar
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }"; // NO: foo= bar ; fruit = apple
/* AJAX CALL PARAMETER:
type: Say to the servlet path, the request is a POST HTTP Request
url: The address to which to send the call
data: the content of my data variable
contentType: an object having JSON format
dataType: the type of content returned by the server
*/
$.ajax({ type: "POST", url: form.attr("action"), data: data, contentType: "application/json", dataType: "text",
success: function(text) { MvcUtil.showSuccessResponse(text, button); },
error: function(xhr) { MvcUtil.showErrorResponse(xhr.responseText, button); }});
return false;
});
The JSON object that I have create and passed is represented by the data variable and contain the following key\value: { \"foo\": \"bar\", \"fruit\": \"apple\" }
我创建并传递的 JSON 对象由 data 变量表示并包含以下键\值:{ \"foo\": \"bar\", \"fruit\": \"apple\" }
Something like:
就像是:
foo: bar
富:酒吧
fruit: apple
水果:苹果
Now, in my controller I have the method that handles this request:
现在,在我的控制器中,我有处理这个请求的方法:
@RequestMapping(value="/mapping/consumes", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String byConsumes(@RequestBody JavaBean javaBean) {
return "Mapped by path + method + consumable media type (javaBean '" + javaBean + "')";
}
So it is clear for me that this method handles HTTP Post Request towards "mapping/consumes" path (only POST Request) but I am not sure about the meaning of the following items:
所以我很清楚这个方法处理 HTTP Post 请求到“映射/消耗”路径(仅 POST 请求),但我不确定以下项目的含义:
consumes=MediaType.APPLICATION_JSON_VALUE: what exactly does this mean? I think that it says to Spring that this method receives an object in JSON format, so it can be parsed in some way...but I am not sure about it and I have not found it in the documentation.
What is consumes? a variable or something like an annotation? I am not understanding things because here it is a parameter of the @RequestMapping annotation but searching on Google shows it is used as a standalone annotation...
In my byConsumes() method I have the following input parameter: @RequestBody JavaBean javaBean. Reading the Spring documentation I understand that: @RequestBody method parameter annotation indicates that using @RequestBody annotation a method parameter should be bound to the value of the HTTP request body.
So in practice this thing mean that I have my JSON object inside my HTTP Request body field and using this annotation I am converting it in an object named javaBean having class JavaBean?
If my affirmation is true...what kind of object is a JavaBean type object? an object that contains only a number of variables and the corresponding getter and setter methods? (in the previus case an object that contain only two variable: the first one named foo and having value "bar", the second one having name fruit and having value "apple")
消费=MediaType.APPLICATION_JSON_VALUE:这到底是什么意思?我认为它对 Spring 说这个方法接收一个 JSON 格式的对象,所以它可以以某种方式解析......但我不确定它,我还没有在文档中找到它。
什么是消费?变量或诸如注释之类的东西?我不明白的事情,因为这里它是@RequestMapping 注释的一个参数,但在谷歌上搜索显示它被用作一个独立的注释......
在我的 byConsumes() 方法中,我有以下输入参数:@RequestBody JavaBean javaBean。阅读Spring文档我明白:@RequestBody方法参数注释表明使用@RequestBody注释方法参数应该绑定到HTTP请求正文的值。
所以在实践中,这意味着我在我的 HTTP 请求正文字段中有我的 JSON 对象,并且使用这个注释我将它转换为一个名为 javaBean 的对象,它具有类 JavaBean?
如果我的肯定是真的……JavaBean 类型的对象是什么类型的对象?一个只包含一些变量和相应的 getter 和 setter 方法的对象?(在前面的例子中,一个只包含两个变量的对象:第一个名为 foo 并具有值“bar”,第二个名为 Fruit 并具有值“apple”)
is it right?
这样对吗?
Thank you very much Andrea
非常感谢安德里亚
回答by Niall Thomson
Your interpretation of what this code is doing is essentially correct.
你对这段代码所做的解释基本上是正确的。
'Consumes' is a parameter of the annotation @RequestMapping
which is used to indicate the HTTP content type that the method handles. In this case it is indicating to Spring that the method takes JSON as input. You can read more about this in the Spring documentation here. You could similarly indicate that a method 'consumes' XML.
'Consumes' 是注解的一个参数,@RequestMapping
用于指示该方法处理的 HTTP 内容类型。在这种情况下,它向 Spring 表明该方法将 JSON 作为输入。您可以在此处的 Spring 文档中阅读有关此内容的更多信息。您可以类似地指示方法“使用”XML。
As for @RequestBody
annotation, this is used to indicate the annotated method parameter should be composed from the body of the HTTP request, the documentation for it is here. Spring will usually do this by taking the name of the HTTP parameter in the request and setting the value in the Java bean using a setter method.
至于@RequestBody
注解,这用于指示被注解的方法参数应该由 HTTP 请求的主体组成,其文档在这里。Spring 通常会通过获取请求中 HTTP 参数的名称并使用 setter 方法在 Java bean 中设置值来完成此操作。
In your example, Spring will inspect the annotations of the method and determine that the request body should be mapped to an object of type JavaBean
. It will create an instance of that class automatically, and (via a Message Converter) will populate the JavaBean
instance. Spring will use reflection to do all of this, but the code it executes would essentially do this:
在您的示例中,Spring 将检查该方法的注释并确定应将请求正文映射到类型为 的对象JavaBean
。它将自动创建该类的实例,并且(通过消息转换器)将填充该JavaBean
实例。Spring 将使用反射来完成所有这些,但它执行的代码基本上会这样做:
JavaBean parameter = new JavaBean();
parameter.setFoo("bar");
parameter.setFruit("apple");
You could swap out the JavaBean
type for any other Java class that declares getters/setters for fields foo
and fruit
.
您可以JavaBean
为任何其他声明字段foo
和.getter/setter 的 Java 类替换类型fruit
。