Spring POST 数据映射到 Entity 保存的简化写法 @RequestBody

发布时间: 2020-11-26 11:03:55 作者: 大象笔记

以保存文章 Article 为例,假设前端只传递两个参数

写法一

在 Spring 后台 Controller 中,逐一参数进行设置,并保存。

前提是,请求是通过查询参数来提及数据。例如:

POST http://localhost/addArticle?title=test&slug=test

@PostMapping("/addArticle")
public String addArticle(@RequestParam String title, @RequestParam String slug) {
    Article article = new Article();
    article.setTitle(title);
    article.setSlug(slug);
    articleRepository.save(article);
    return "added";
}

在参数较多的情况下,这种写法非常繁琐。

写法二,简化版

这种写法就简洁非常多,但是也是有前提的,需要通过 POST JSON 格式的数据。

格式参考:IDEA IDE 中模拟发送 JSON POST 请求

@PostMapping("/addArticle")
public String addArticle(@RequestBody Article article) {
    articleRepository.save(article);
    return "added1";
}

RequestBody 的说明

Annotation indicating a method parameter should be bound to the body of the web request.

RequestParam,RequestBody 与 RequestPart 的区别

注意三者对应的 HTTP 请求头也不同:

我是一名山东烟台的开发者,联系作者