This example shows how to handle HTTP PATCH request in Spring MVC
PUT vs PATCH vs POST
PUT method creates/replaces the resource at the requested URI.
PATCH method modifies the existing resource (partially) at the requested URI.
POST method creates/modifies the resource without targeting an URI. After modification, how user can make use of the same resource, that's entirely dependent on the web application logic.
Example
The controller
@Controller
@RequestMapping("/articles")
public class ArticleController {
@Autowired
private ArticleService articleService;
@PatchMapping("/{id}")
@ResponseBody
public String patchArticle(@RequestBody MultiValueMap<String, String> formParams) {
System.out.println(formParams);
long id = Long.parseLong(formParams.getFirst("id"));
String content = formParams.getFirst("content");
articleService.updateArticle(id, content);
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(long id, String content) {
this.id = id;
this.content = content;
}
.............
}
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>Article Form</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/>
<script>
$("#article-form").submit(function(event){
event.preventDefault();
var form = $(this);
var id = form.find('input[name="id"]').val();
var url = 'http://localhost:8080/articles/'+id;
var content = form.find('input[name="content"]').val();
$.ajax({
type : 'PATCH',
url : url,
contentType: 'application/x-www-form-urlencoded',
data : "id=" + id + "&content=" + content,
success : function(data, status, xhr){
//refresh the current page
location.reload();
},
error: function(xhr, status, error){
alert(error);
}
});
});
</script>
</body>
</html>
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/1 :
Editing the content form field and submitting the form will refresh the form with updated content:
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.3.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- jstl 1.2 javax.servlet:jstl
- JDK 1.8
- Maven 3.3.9
|