This tutorial shows how to handle JSON body data of HTTP PUT request in Spring MVC
Example
The controller
@Controller
@RequestMapping("/articles")
public class ArticleController {
@Autowired
private ArticleService articleService;
@GetMapping
public String getArticleForm() {
return "article-form";
}
@PutMapping("/{id}")
@ResponseBody
public String createNewArticle(@RequestBody Article article) {
articleService.saveArticle(article);
return "Article created.";
}
@GetMapping("/{id}")
public String getArticle(@PathVariable("id") long id, Model model) {
Article article = articleService.getArticleById(id);
model.addAttribute("article", article);
return "article-page";
}
}
public class Article {
private long id;
private String 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 PUT request with JSON Body Example</h3>
<form id="article-form">
<pre>
id: <input type="text" name="id">
content: <input type="text" name="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 : 'PUT',
url : url,
contentType: 'application/json',
data : jsonString,
success : function(data, status, xhr){
$("#result").html(data+
" link: <a href='"+url+"'>"+url+"</a>");
},
error: function(xhr, status, error){
alert(error);
}
});
});
</script>
</body>
</html>
src/main/webapp/WEB-INF/views/article-page.jsp<html>
<body>
<h3>Article</h3>
${article}
</form>
</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
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Accessing http://localhost:8080/articles:
Filling up and submitting the form:
In Chrome's developer tools window, we will see the logs:
Clicking on the hyper link of the article:
Example ProjectDependencies 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
|