【问题标题】:PostMapping with Parameters from URI使用 URI 中的参数进行 PostMapping
【发布时间】:2019-10-18 09:25:01
【问题描述】:

我正在尝试构建一个从 uri 获取参数的 spring boot @PostMapping 方法,类似这样 http://localhost:8091/url/log?param1=asdf&param2=asd&param3=test 或者像这样 http://localhost:8091/url/log/msg/msg1/msg2

有没有办法将代码模型从下面扩展到3个参数? headers.setLocation(builder.path("/article/{param1}/{param2}/{param3}")

@PostMapping("article")
    public ResponseEntity<Void> addArticle(@RequestBody ArticleInfo articleInfo, UriComponentsBuilder builder) {
        Article article = new Article();
        BeanUtils.copyProperties(articleInfo, article);


            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri());
            return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

【问题讨论】:

  • 首先:您的帖子调用应该有请求参数。 http://localhost:8091/url/log?param1=asdf&amp;param2=asd&amp;param3=test 是一种不好的做法。第二:http://localhost:8091/url/log/msg/msg1/msg2 是一个好方法更好的方法是创建一个 Request json 对象
  • 问题是我在 ArticleRepository 之前没有使用@Autowired :(
  • 我现在将使用 Sovannarith 方法,我太笨了。也许它会帮助其他人。

标签: java spring-boot


【解决方案1】:

如果您只是希望您的 API 调用来创建新文章,那么简单地将 PostMapping 设置为 /article/new(例如)然后简单地将新文章的参数作为 RequestBody 传递?

@PostMapping("article/new")
public ResponseEntity<Void> addArticle(@RequestBody Article article) {
// ...
}

然后作为 RequestBody 你会得到类似的东西:

{ "param1": "value1", "param2": "value2", "param3": "value3" }

如果您只是想在 api 调用中包含更多 PathVariable,请参阅 @sovannarith cheav 的回答

希望对你有帮助

【讨论】:

  • 如果RequestBody中的参数正确,会自动映射到Article对象,所以只需添加自己的逻辑来保存article对象即可。我会使用带有保存方法的服务,例如:articlesService.save(article);
【解决方案2】:

有没有办法将代码模型从下面扩展到3个参数? headers.setLocation(builder.path("/article/{param1}/{param2}/{param3}")

您可以使用@PathVariable,如下所示

@PostMapping("article/{param1}/{param2}/{param3}")
public ResponseEntity<Void> addArticle(@PathVariable("param1") String param1, @PathVariable("param3") String param3, @PathVariable("param3") String param3) {
    //enter code here
}

【讨论】:

  • 您的参数主要用于获取调用。您永远不想在要保存的 url 中公开数据
  • @NaveenKulkarni 我只是给他想要的! :(
  • 这里的论坛不仅仅是给他/她想要的。如果他们以错误的方式进行操作,也可以纠正他们。
猜你喜欢
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 2020-07-30
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多