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

文章目录

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

    • 文章标题 title
    • 文章链接 slug

    写法一

    在 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 请求头也不同:

    • @RequestParam:请求头 application/x-www-form-urlencoded
    • @RequestBody:请求头 application/json
    • @RequestPart:请求头 multipart/form-data

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式