英文:
What is the difference between parameters in spring boot?
问题
我需要在控制器的@RequestMapping中处理不同类型的参数。例如,你如何区分以下路径:
/posts
/posts/1
/posts&userId=1
前两者之间似乎可以工作,但调用第三者会导致“模糊映射”错误。
以下是控制器代码:
@RequestMapping(value= {"/posts", "/posts/{numberOfPosts}"})
public String getBlogPosts(@PathVariable Optional<Integer> numberOfPosts) { //为了防止“模糊映射”错误
if (numberOfPosts.isPresent()) {
return blogService.getUserBlogPosts(numberOfPosts);
}
else {
return blogService.getAllBlogPosts();
}
}
以下是第三者:
@RequestMapping("/posts")
public String getUserIdPosts(@RequestParam int userId) {
return blogService.getUserIdPosts(userId);
}
我该如何处理第三个问题?
英文:
I'm required to handle different types of parameters in the @RequestMapping of the controller. For example, how do you differentiate between
/posts
/posts/1
/posts&userId=1
This seems to work between the first two but calling the third one results in "Ambiguous mapping" error.
Here is the controller code:
@RequestMapping(value= {"/posts", "/posts/{numberOfPosts}"})
public String getBlogPosts(@PathVariable Optional<Integer> numberOfPosts) { //to prevent "Ambiguous mapping" error
if (numberOfPosts.isPresent()) {
return blogService.getUserBlogPosts(numberOfPosts);
}
else {
return blogService.getAllBlogPosts();
}
}
Here is the third one:
@RequestMapping("/posts")
public String getUserIdPosts(@RequestParam int userId) {
return blogService.getUserIdPosts(userId);
//return blogService.getUserBlogPosts(numberOfPosts);
}
How do I handle the third one?
答案1
得分: 0
/path和
/post&userId=1 的路径映射是相同的:
/post`。
您可以通过在代码中对 userId
变量进行测试来区分这两个 URL,示例如下:
@RequestMapping(value= {"/posts", "/posts/{numberOfPosts}"}, method = RequestMethod.GET)
public String getBlogPosts(@PathVariable(required = false) Optional<Integer> numberOfPosts, @RequestParam(required = false) Integer userId) {
if (numberOfPosts.isPresent()) {
return blogService.getUserBlogPosts(numberOfPosts);
}
else if(userId == null) {
return blogService.getAllBlogPosts();
} else {
return blogService.getUserIdPosts(userId);
}
}
别忘了通过在上述注解中添加 required = false
,使请求的参数 userId
和路径变量 numberOfPosts
成为可选项。
英文:
The path mapping for /post
and /post&userId=1
are the same: /post
.
You can handle make the difference between these two URLs in your code by testing on the userId
variable like below:
@RequestMapping(value= {"/posts", "/posts/{numberOfPosts}"}, method = RequestMethod.GET)
public String getBlogPosts(@PathVariable(required = false) Optional<Integer> numberOfPosts, @RequestParam(required = false) Integer userId) {
if (numberOfPosts.isPresent()) {
return blogService.getUserBlogPosts(numberOfPosts);
}
else if(userId == null) {
return blogService.getAllBlogPosts();
} else {
return blogService.getUserIdPosts(userId);
}
}
Don't forger to make the requested parameter userId
and the path variable numberOfPosts
optional by adding required = false
to the above annotations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论