Close

Spring MVC - Mapping JSON body data of HTTP PATCH request to Java Object

[Last Updated: Feb 23, 2018]

This tutorial shows how to handle JSON body data of HTTP PATCH request in Spring MVC.

Example

The controller

@Controller
@RequestMapping("/articles")
public class ArticleController {

  @Autowired
  private ArticleService articleService;

  @PatchMapping("/{id}")
  @ResponseBody
  public String patchArticle(@RequestBody Article article) {
      articleService.updateArticle(article.getId(), article.getContent());
      return "Article updated.";
  }

  @GetMapping("/{id}")
  public String getArticle(@PathVariable("id") long id, Model model) {
      Article article = articleService.getArticleById(id);
      model.addAttribute("article", article);
      return "article-form";
  }
}
public class Article {
  private long id;
  private String content;

  public Article() {
  }

  public Article(int id, String content) {
      this.id = id;
      this.content = content;
  }
    .............
}

JSP Pages

src/main/webapp/WEB-INF/views/article-form.jsp

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<h3>HTTP PATCH request with JSON Body Example</h3>
<form id="article-form">
    <pre>
         id: <input type="text" name="id" value="${article.id}" readonly>
    content: <input type="text" name="content" value="${article.content}">
                  <input type="submit" value="Submit">
    </pre>
</form>
<br/>
<div id="result"></div>

<script>
 $("#article-form").submit(function(event){
            event.preventDefault();
            var form = $(this);
            var idVal = form.find('input[name="id"]').val();
            var contentVal = form.find('input[name="content"]').val();
            var url = 'http://localhost:8080/articles/'+idVal;
            var jsonString = JSON.stringify({id: idVal, content: contentVal});
            console.log(jsonString);
            $.ajax({
                type : 'PATCH',
                url : url,
                contentType: 'application/json',
                data : jsonString,
                success : function(data, status, xhr){
                   //refresh the current page
                   location.reload();
                },
                error: function(xhr, status, error){
                  alert(error);
                }
            });
        });
</script>
</body>
</html>

Additional JSON dependency

pom.xml

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.2</version>
</dependency>

Java Config

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

  @Override
  public void configureViewResolvers(ViewResolverRegistry registry) {
      registry.jsp("/WEB-INF/views/", ".jsp");
  }
}

Output

The output is same as the last example.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.3.RELEASE: Spring Web MVC.
  • jackson-databind 2.9.4: General data-binding functionality for Jackson: works on core streaming API.
  • javax.servlet-api 3.0.1 Java Servlet API
  • jstl 1.2 javax.servlet:jstl
  • JDK 1.8
  • Maven 3.3.9

HTTP JSON PATCH Request Example Select All Download
  • spring-patch-json-body-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views
              • article-form.jsp

    See Also