title: Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how to get it right once for all?
body: <p>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. </p>
  
  <h2>Related Concepts</h2>
  
  <p>Surely you know about these but I just write them as a quick review. Feel free to edit in case I am missing something.</p>
  
  <h3>HTTP POST Request:</h3>
  
  <p>A post request is used when you are willing to send an object to a web service or a your server side application.</p>
  
  <h3>Serialization:</h3>
  
  <p>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.</p>
  
  <h3>Serialization protocols:</h3>
  
  <p>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 <a href="https://stackoverflow.com/questions/3979649/json2-vs-jquery-json">JSON2</a> serialization. </p>
  
  <h3>Spring:</h3>
  
  <p>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 <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody" rel="noreferrer">Spring web MVC</a>.</p>
  
  <h3>Curl vs JQuery:</h3>
  
  <p>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. </p>
  
  <h3>@RequestBody vs @RequestParam/@PathVariable vs @ModelAttribute:</h3>
  
  <p>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. </p>
  
  <h3>@RequestBody vs @ResposeBody:</h3>
  
  <p>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.</p>
  
  <h3>RequestMappingHandlerAdapter vs AnnotationMethodHandlerAdapter:</h3>
  
  <p>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.</p>
  
  <h2>Setup</h2>
  
  <p>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.</p>
  
  <p>Basic Configuration from <a href="https://stackoverflow.com/questions/3979649/json2-vs-jquery-json">here</a>. The convertors were MarshallingHttpMessageConverter and CastorMarshaller in the <a href="https://stackoverflow.com/questions/3979649/json2-vs-jquery-json">basic configuration sample</a>, I have replaced them with MappingJackson2HttpMessageConverter and MappingJacksonHttpMessageConverter.</p>
  
  <h3>Where to put the configuration</h3>
  
  <p>The way my project is set up, I have two config files:</p>
  
  <ul>
  <li>Application Context XML:
  One it the application context XML file where your sessionFactory bean, dataSource bean, etc. are located.</li>
  <li>MVC Dispatcher Servlet XML:
  This is where you have your view resolver bean and import your application context XML.</li>
  </ul>
  
  <p>hadlerAdapter bean has to be located in the later that is the MVC Dispatcher XML file. </p>
  
  <pre><code>&lt;bean name="handlerAdapter"
  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"&gt;
      &lt;property name="messageConverters"&gt;
          &lt;list&gt;
              &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/&gt;
              &lt;ref bean="jsonConverter"/&gt;
  
          &lt;/list&gt;
  
      &lt;/property&gt;
      &lt;property name="requireSession" value="false"/&gt;
  
  &lt;/bean&gt;
  &lt;bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"&gt;
      &lt;property name="supportedMediaTypes" value="application/json"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>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).</p>
  
  <h2>REST API</h2>
  
  <p>Here is a sample controller that is exposing the REST API.</p>
  
  <h3>The controller</h3>
  
  <p>This is where your REST API for a HTTP post request is exposed.</p>
  
  <pre><code>@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-&gt; {" + user.toString() + "} is added";
      System.out.println(userAdded);
          return userAdded;
      }
  }
  </code></pre>
  
  <h3>The Java Object</h3>
  
  <pre><code>@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()  + " | ";
      }
  
  }
  </code></pre>
  
  <h3>CURL Post call</h3>
  
  <pre><code>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
  </code></pre>
  
  <h1>Related posts and questions</h1>
  
  <p>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):</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type?rq=1">What is the <em>correct</em> JSON content type?</a></li>
  <li><a href="https://stackoverflow.com/questions/2259551/spring-3-0-making-json-response-using-jackson-message-converter?rq=1">Spring 3.0 making JSON response using jackson message converter</a></li>
  <li><a href="https://stackoverflow.com/questions/7172784/how-to-post-json-data-with-curl-from-terminal-commandline-to-test-spring-rest">How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?</a></li>
  <li><a href="https://stackoverflow.com/questions/10323957/posting-json-to-rest-api">Posting JSON to REST API</a></li>
  <li><a href="https://github.com/geowarin/spring-mvc-examples" rel="noreferrer">https://github.com/geowarin/spring-mvc-examples</a></li>
  <li><a href="https://stackoverflow.com/questions/813487/how-to-post-json-to-php-with-curl">How to post JSON to PHP with curl</a></li>
  <li><a href="https://stackoverflow.com/questions/5613566/spring-rest-mappingjacksonhttpmessageconverter-produces-invalid-json">Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON</a></li>
  <li><a href="https://github.com/eugenp/REST" rel="noreferrer">https://github.com/eugenp/REST</a></li>
  <li><a href="https://stackoverflow.com/questions/6203740/spring-web-mvc-validate-individual-request-params?rq=1">Spring Web MVC - validate individual request params</a></li>
  <li><a href="https://stackoverflow.com/questions/7172784/how-to-post-json-data-with-curl-from-terminal-commandline-to-test-spring-rest?rq=1">How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?</a></li>
  <li><a href="https://stackoverflow.com/questions/2010990/how-do-you-return-a-json-object-from-a-java-servlet?lq=1">How do you return a JSON object from a Java Servlet</a></li>
  <li><a href="https://stackoverflow.com/questions/404470/what-mime-type-if-json-is-being-returned-by-a-rest-api">What MIME type if JSON is being returned by a REST API?</a></li>
  </ol>