学习春天的@RequestBody和@RequestParam
2022-09-03 06:27:07
我正在编辑一个使用Spring的Web项目,我需要添加一些Spring的注释。我要添加的两个是@RequestBody和@RequestParam。我一直在四处寻找并发现了这一点,但我仍然不完全了解如何使用这些注释。任何人都可以举个例子吗?
我正在编辑一个使用Spring的Web项目,我需要添加一些Spring的注释。我要添加的两个是@RequestBody和@RequestParam。我一直在四处寻找并发现了这一点,但我仍然不完全了解如何使用这些注释。任何人都可以举个例子吗?
控制器示例:
@Controller
class FooController {
@RequestMapping("...")
void bar(@RequestBody String body, @RequestParam("baz") baz) {
//method body
}
}
@RequestBody:变量主体将包含 HTTP 请求的主体
@RequestParam:变量 baz 将保存请求参数 baz 的值
@RequestParam带注释的参数链接到特定的 Servlet 请求参数。参数值将转换为声明的方法参数类型。此注释指示方法参数应绑定到 Web 请求参数。
例如,对 Spring RequestParam 的 Angular 请求将如下所示:
$http.post('http://localhost:7777/scan/l/register', {params: {"username": $scope.username, "password": $scope.password, "auth": true}}).
success(function (data, status, headers, config) {
...
})
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
public Map<String, String> register(Model uiModel,
@RequestParam String username, @RequestParam String password, boolean auth,
HttpServletRequest httpServletRequest) {...
@RequestBody带注释的参数都链接到 HTTP 请求正文。参数值使用 HttpMessageConverters 转换为声明的方法参数类型。此注释指示方法参数应绑定到 Web 请求的正文。
例如,对 Spring RequestBody 的 Angular 请求如下所示:
$scope.user = {
username: "foo",
auth: true,
password: "bar"
};
$http.post('http://localhost:7777/scan/l/register', $scope.user).
success(function (data, status, headers, config) {
...
})
@RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
public Map<String, String> register(Model uiModel,
@RequestBody User user,
HttpServletRequest httpServletRequest) {...
希望这有帮助。