首页 > 解决方案 > @requestMapping 和 @requestParam 的属性参数的区别

问题描述

我发现@requestMapping和@requestParam的属性参数都可以实现绑定方法参数到URL地址?那么在一般情况下它们可以相互替换吗?

标签: springspring-mvc

解决方案


也许你应该用例子详细说明你的问题。

总之,@RequestMapping 参数和@RequestParams 通常用于不同的目的

我们举个例子:https : //stackoverflow.com/questions/63871895

在这个 URI 中,我们可以在一个控制器中看到两个不同的处理程序。

@RequestMapping(path = "/questions/{id}", method = RequestMethod.GET)
public Question getQuestion(@PathVariable int id) {
// returns a particular question
}

@RequestMapping(path = "/questions", method = RequestMethod.GET)
public List<Question> getQuestions() {
// returns all questions
}

现在在这里,参数映射被视为强制执行的限制。主路径映射(即指定的 URI 值)仍然必须唯一标识目标处理程序,参数映射仅表示调用处理程序的先决条件。

现在,让我们看一个@RequestParams 的示例:https ://www.google.com/search?client=opera&q=stackoverflow&sourceid=opera&ie=UTF-8&oe=UTF-8

在这个 URL 中,我们可以看到一个处理程序:

@RequestMapping(path = "/search", method = RequestMethod.GET)
public List<Results> getResults(@RequestParam Map allRequestParams) {
// returns results based on query parameters
}  

无论是否提供查询参数,这将始终调用相同的处理程序。因此,@RequestParams 用于从 URL 中提取查询参数。

因此,通常,您可以尝试使用@RequestMapping 参数代替@RequestParams,但它会产生上述示例中解释的效果。

来源https ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html


推荐阅读