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.
HTTP POST请求:
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 post请求.
序列化协议:
现在最流行的是JSON和XML.XML正变得越来越不受欢迎,因为由于XML标记的性质,序列化的XML对象在大小上相对较大.在本常见问题解答中,主要焦点是JSON2序列化.
春天:
Spring框架及其强大的注释使得以高效的方式公开Web服务成为可能.Spring有很多不同的图书馆.我们在这里关注的是Spring web MVC.
Curl vs JQuery:
这些是您可以用来在客户端发出post请求的工具.即使您计划使用jQueryAjax调用,我建议您出于调试目的使用Curl,因为它在发出post请求后为您提供了详细的响应.
@RequestBody vs@RequestParam/@PathVariable vs@ModelAttribute:
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.
@RequestBody vs @ResposeBody:
从名称可以看出,它就这么简单,如果在服务器端方法处理请求后向客户端发送响应,则只需要@ResponseBody.
RequestMappingHandlerAdapter vs AnnotationMethodHandlerAdapter:
RequestMappingHandlerAdapter是Spring框架的新映射处理程序,从Spring3.1开始取代了AnnotationMethodHandlerAdapter.如果您的现有配置仍在AnnotationMethodHandlerAdapter中,您可能会发现这篇文章很有用.我的帖子中提供的配置将让您了解如何设置RequestMappingHandlerAdapter.
设置
您需要设置一个消息转换器.这就是在服务器端将序列化的JSON消息体转换为本地java对象的方式.
从here开始的基本配置.basic configuration sample中的转换器是MarshallingHttpMessageConverter和CastorMarshaller,我将它们替换为MappingJackson2HttpMessageConverter和MappingJacksonHttpMessageConverter.
配置放在哪里
The way my project is set up, I have two config files:
- 应用程序上下文XML: 其中之一是您的sessionFactory bean、DataSource bean等所在的应用程序上下文XML文件.
- MVC Dispatcher Servlet XML: This is where you have your view resolver bean and import your application context 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>
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).
睡觉接口
下面是一个示例控制器,它公开了睡觉接口.
The controller
这就是HTTP post请求的睡觉接口公开的地方.
@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 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
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):
- What is the correct JSON content type?
- Spring 3.0 making JSON response using jackson message converter个
- How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
- Posting JSON to 睡觉接口
- https://github.com/geowarin/spring-mvc-examples
- How to post JSON to PHP with curl
- Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON
- https://github.com/eugenp/REST
- Spring Web MVC - validate individual request params
- How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
- How do you return a JSON object from a Java Servlet
- What MIME type if JSON is being returned by a 睡觉接口?