Spring 4.x/3.x (Web MVC) REST API 和 JSON2 Post 请求,如何一劳永逸? [英] Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how to get it right once for all?

查看:30
本文介绍了Spring 4.x/3.x (Web MVC) REST API 和 JSON2 Post 请求,如何一劳永逸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在详细介绍之前,我知道在 Stackoverflow 上已经有很多对话和相关问题.所有这些都以不同的方式帮助我,所以我想我把我的发现放在一起作为一个单一的有组织的常见问题解答来总结我的发现.

Before going into details, I know there has been lots of conversations and related questions on Stackoverflow. All of them kind of help me in different ways so I thought I put my findings all together as a single organized FAQ to summarize my findings.

您当然知道这些,但我只是将它们写为快速回顾.如有遗漏,请随时编辑.

Surely you know about these but I just write them as a quick review. Feel free to edit in case I am missing something.

当您愿意将对象发送到 Web 服务或服务器端应用程序时,将使用发布请求.

A post request is used when you are willing to send an object to a web service or a your server side application.

是将对象从 Web 浏览器获取到服务器端应用程序的过程.可以使用 jQuery Ajax 调用或 Curl 发布请求.

Is the process of getting the object from your web browser through to your server side application. A jQuery Ajax call or a Curl post request can be used.

最近最流行的是 JSON 和 XML.由于 XML 标记的性质,序列化 xml 对象的大小相对较大,因此 XML 变得越来越不流行.在这个 FAQ 中,主要焦点是 JSON2 序列化.

The most popular ones theses days are JSON and XML. XML is becoming less popular as serialized xml objects are relatively bigger in size due the the nature of XML tagging. In this FAQ the main focus is JSON2 serialization.

Spring 框架及其强大的注释使得以高效的方式公开 Web 服务成为可能.Spring 中有很多不同的库.我们在这里的重点是 Spring Web MVC.

Spring framework and its powerful annotation makes it possible to expose web service in an efficient way. There are a lot of different libraries in Spring. The one that is our focus here is Spring web MVC.

这些是您可以用来在客户端发出发布请求的工具.即使您打算使用 JQuery ajax 调用,我建议您使用 Curl 进行调试,因为它会在发出 post 请求后为您提供详细的响应.

These are the tools you can use to make a post request in your client side. Even if you are planning to use JQuery ajax call, I suggest you use Curl for debugging purposes as it provides you with a detailed response after making the post request.

如果您的 Web 服务不依赖于您的 Java EE 模型,则必须使用 @RequestBody.如果您正在使用模型并且您的 JSON 对象已添加到模型中,则您可以通过 @ModelAttribute 访问该对象.仅当您的请求是 GET 请求或 GET 和 POST 请求组合时,您才需要使用@RequestParam/@PathVariable.

In cases where you have a web service that is not depending on your Java EE model, @RequestBody must be used. If you are using the model and your JSON object is added to the model, you can access the object through @ModelAttribute. Only for cases where your request is either a GET request or a GET and POST request combination you will need to use @RequestParam/@PathVariable.

正如您从名称中看到的那样简单,如果您在服务器端方法处理请求后向客户端发送响应,则只需要@ResponseBody.

As you can see from the name it as simple as that, you only need the @ResponseBody if you are sending a response the the client after the server side method processed the request.

RequestMappingHandlerAdapter 是 Spring 框架的新映射处理程序,自 Spring 3.1 起取代了 AnnotationMethodHandlerAdapter.如果您现有的配置仍在 AnnotationMethodHandlerAdapter 中,您可能会发现这篇文章很有用.我的帖子中提供的配置将让您了解如何设置 RequestMappingHandlerAdapter.

RequestMappingHandlerAdapter is the new mapping handler for Spring framework that replaced AnnotationMethodHandlerAdapter since Spring 3.1. If your existing configuration is still in AnnotationMethodHandlerAdapter you might find this post useful. The config provided in my post will give you an idea on how to set up the RequestMappingHandlerAdapter.

您需要设置一个消息转换器.这就是您的序列化 JSON 消息正文在您的服务器端转换为本地 java 对象的方式.

You will need to setup a message convertor. This is how your serialized JSON message body is converted into a local java object at your server side.

来自此处的基本配置.转换器是 基本配置示例中的 MarshallingHttpMessageConverter 和 CastorMarshaller,我已将它们替换为 MappingJackson2HttpMessageConverter 和 MappingJacksonHttpMessageConverter.

Basic Configuration from here. The convertors were MarshallingHttpMessageConverter and CastorMarshaller in the basic configuration sample, I have replaced them with MappingJackson2HttpMessageConverter and MappingJacksonHttpMessageConverter.

我的项目设置方式,我有两个配置文件:

The way my project is set up, I have two config files:

  • 应用程序上下文 XML:其中之一是 sessionFactory bean、dataSource bean 等所在的应用程序上下文 XML 文件.
  • MVC 调度程序 Servlet XML:这是您拥有视图解析器 bean 并导入应用程序上下文 XML 的地方.

hadlerAdapter bean 必须位于 MVC Dispatcher XML 文件中.

hadlerAdapter bean has to be located in the later that is the MVC Dispatcher XML file.

<bean name="handlerAdapter"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            <ref bean="jsonConverter"/>

        </list>

    </property>
    <property name="requireSession" value="false"/>

</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
</bean>

您可以有多个消息转换器.在这里,我创建了一个普通的 JSON 和一个 JSON 2 消息转换器.XML 文件中的 Ref 和普通 bean 格式都已使用(我个人更喜欢 ref 标签,因为它更整洁).

You can have multiple message convertors. here, I have created a normal JSON as well as a JSON 2 message convertor. Both Ref and normal bean format in the XML file have been used (personally I prefer the ref tag as its neater).

这是一个暴露 REST API 的示例控制器.

Here is a sample controller that is exposing the REST API.

这是您用于 HTTP 发布请求的 REST API 公开的地方.

This is where your REST API for a HTTP post request is exposed.

@Component
@Controller
@RequestMapping("/api/user")
public class UserController {
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String insertUser(@RequestBody final User user) {
    System.out.println(user.toString());
    userService.insertUser(user);
    String userAdded = "User-> {" + user.toString() + "} is added";
    System.out.println(userAdded);
        return userAdded;
    }
}

Java 对象

@JsonAutoDetect
public class User {

private int id;
private String username;
private String name;
private String lastName;
private String email;

public int getId() {
    return externalId;
}

public void setId(final int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(final String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(final String email) {
    this.email = email;
}
public String getUsername() {
    return username;
}

public void setUsername(final String username) {
    this.username = username;
}

public String getLastName() {
    return lastName;
}

public void setLastName(final String lastName) {
    this.lastName = lastName;
}

@Override
public String toString() {
    return this.getName() + " | " + this.getLastName()  + " | " + this.getEmail()
            + " | " + this.getUsername()  + " | " + this.getId()  + " | ";
    }

}

CURL 发布调用

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

相关帖子和问题

如果不是所有提供以下帖子和问题的人都无法使用此常见问题解答(如果我遇到有用的相关帖子/问题,此列表将扩大):

Related posts and questions

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

  1. 什么是正确JSON 内容类型?
  2. Spring 3.0 制作 JSON 响应使用杰克逊消息转换器
  3. 如何使用 Curl 从终端/命令行发布 JSON 数据以测试 Spring REST?
  4. 将 JSON 发布到 REST API
  5. https://github.com/geowarin/spring-mvc-examples
  6. 如何使用 curl 将 JSON 发布到 PHP
  7. Spring REST |MappingJacksonHttpMessageConverter 生成无效的 JSON
  8. https://github.com/eugenp/REST
  9. Spring Web MVC - 验证单个请求参数
  10. 如何使用 Curl 从终端/命令行发布 JSON 数据以测试 Spring REST?
  11. 你好吗从 Java Servlet 返回一个 JSON 对象
  12. 如果 JSON 是什么 MIME 类型正在由 REST API 返回?
  1. What is the correct JSON content type?
  2. Spring 3.0 making JSON response using jackson message converter
  3. How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
  4. Posting JSON to REST API
  5. https://github.com/geowarin/spring-mvc-examples
  6. How to post JSON to PHP with curl
  7. Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON
  8. https://github.com/eugenp/REST
  9. Spring Web MVC - validate individual request params
  10. How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
  11. How do you return a JSON object from a Java Servlet
  12. What MIME type if JSON is being returned by a REST API?

推荐答案

CURL Post call

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

不同的错误场景:

在此,我将探讨在进行 curl 调用后您可能会遇到的各种错误以及可能出错的地方.

Different Error Scenarios:

Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong.

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 949
Date: Tue, 04 Jun 2013 02:59:35 GMT

这意味着您提供的 URL 中不存在 REST API.

This implies that the REST API does not exist in the URL you have provide.

  • 您的请求中可能有错别字(相信我会发生这种情况)!
  • 可能是您的弹簧配置不正确.如果是这种情况,则需要进一步深入研究到底出了什么问题,但我已经提供了一些您在开始更复杂的调查之前需要执行的初始操作.

在您确定一切都做得非常正确并且您的配置和 URL 都没有问题之后:- 运行 Maven 清洁.- 取消部署您的网络应用程序或干脆删除它.- 重新部署网络应用- 确保在你的 maven/gradle 中只使用一个版本的 Spring

After you have made sure that everything is done perfectly right and nothing is wrong with your Configuration nor you URL: - Run a maven clean. - Undeploy your web app or simply delete it. - Redeploy the web app - Make sure to use only one version of Spring in your maven/gradle

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 968
Date: Tue, 04 Jun 2013 03:08:05 GMT
Connection: close

这背后的唯一原因是您的请求格式不正确.如果您查看详细的 curl 响应,您应该能够看到客户端发送的请求在语法上不正确.".

The only reason behind this is that fact that your request is not formatted correctly. If you checkout the detailed curl response you should be able to see "The request sent by the client was syntactically incorrect.".

要么您的 JSON 格式不正确,要么您缺少 JAVA 对象的必需参数.

Either your JSON format is not right or you are missing a mandatory parameter for the JAVA object.

确保您以正确的格式和正确数量的参数提供 JSON 对象.Nullable 属性不是强制性的,但您必须为所有 NotNullable 属性提供数据.记住 Spring 正在使用 Java 反射将您的 JSON 文件转换为 Java 对象非常重要,这是什么意思?这意味着变量和方法名称是 CasE SensItiVe.如果您的 JSON 文件发送变量userName",那么您的 Java 对象中的匹配变量也必须命名为userName".如果您有 getter 和 setter,它们也必须遵循相同的规则.getUserName 和 setUserName 以匹配我们之前的示例.

Make sure you provide the JSON object in correct format and with the right number of parameters. Nullable properties are not mandatory but you do have to provide data for all NotNullable properties. It is VERY important to remember that Spring is using Java reflection to turn yours JSON file into Java objects, what does this mean? it means that variable and method names are CasE SensItiVe. If your JSON file is sending the variable "userName", than your matching variable in your Java object MUST also be named "userName". If you have getters and setters, they also have to follow the same rule. getUserName and setUserName to match our previous example.

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

根本原因:

您的网络服务不支持 Json 媒体类型.这可能是由于您的注释未指定媒体类型或您未在 Curl post 命令中指定媒体类型.

Root cause:

The Json media type is not supported by your web service. This could be due to your annotation not specifying the media type or you not specifying the media type in Curl post command.

检查您的消息转换器设置是否正确,并确保网络服务注释与上面的示例相匹配.如果这些都没有问题,请确保在 Curl 发布请求中指定内容类型.

Check your message convertor is set up correctly and make sure the web service annotation matches the example above. If these were fine, make sure you specify the content-type in your Curl post request.

您的网络服务不支持 json 媒体类型.

The json media type is not supported by your web service.

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Content-Type: application/json;charset=UTF-8 
Transfer-Encoding: chunked 
Date: Tue, 04 Jun 2013 03:06:16 GMT 

恭喜用户实际发送到您的服务器端 REST API.

Congrats the user is actually send to your server side REST API.

有关如何设置 spring 检查的更多详细信息,请参阅 spring mvc 指南.

For further details on how to set up your spring checkout the spring mvc guide.

如果不是所有提供以下帖子和问题的人都无法使用此常见问题解答(如果我遇到有用的相关帖子/问题,此列表将扩大):

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

  1. 什么是正确JSON 内容类型?
  2. Spring 3.0 制作 JSON 响应使用杰克逊消息转换器
  3. 如何使用 Curl 从终端/命令行发布 JSON 数据以测试 Spring REST?
  4. 将 JSON 发布到 REST API
  5. https://github.com/geowarin/spring-mvc-examples
  6. 如何使用 curl 将 JSON 发布到 PHP
  7. Spring REST |MappingJacksonHttpMessageConverter 生成无效的 JSON
  8. https://github.com/eugenp/REST
  9. Spring Web MVC - 验证单个请求参数
  10. 如何使用 Curl 从终端/命令行发布 JSON 数据以测试 Spring REST?
  11. 你好吗从 Java Servlet 返回一个 JSON 对象
  12. 如果 JSON 是什么 MIME 类型正在由 REST API 返回?
  1. What is the correct JSON content type?
  2. Spring 3.0 making JSON response using jackson message converter
  3. How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
  4. Posting JSON to REST API
  5. https://github.com/geowarin/spring-mvc-examples
  6. How to post JSON to PHP with curl
  7. Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON
  8. https://github.com/eugenp/REST
  9. Spring Web MVC - validate individual request params
  10. How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
  11. How do you return a JSON object from a Java Servlet
  12. What MIME type if JSON is being returned by a REST API?

这篇关于Spring 4.x/3.x (Web MVC) REST API 和 JSON2 Post 请求,如何一劳永逸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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