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.
Related Concepts
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 Request:
A post request is used when you are willing to send an object to a web service or a your server side application.
Serialization:
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.
Serialization protocols:
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:
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.
Curl vs JQuery:
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.
@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:
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 vs AnnotationMethodHandlerAdapter:
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.
Setup
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.
Basic Configuration from here. The convertors were MarshallingHttpMessageConverter and CastorMarshaller in the basic configuration sample, I have replaced them with MappingJackson2HttpMessageConverter and MappingJacksonHttpMessageConverter.
Where to put the configuration
The way my project is set up, I have two config files:
- Application Context XML:
One it the application context XML file where your sessionFactory bean, dataSource bean, etc. are located.
- 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).
REST API
Here is a sample controller that is exposing the REST API.
The controller
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;
}
}
The Java Object
@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":"[email protected]"}' 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 REST API
- 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 REST API?
See Question&Answers more detail:
os