Java 学习春天&x27;s@RequestBody和@RequestParam
我正在编辑一个使用Spring的web项目,我需要添加一些Spring的注释。我要添加的两个是和。我已经摸索了一下,发现了一些问题,但我仍然不完全理解如何使用这些注释。有人能举个例子吗?控制器示例:Java 学习春天&x27;s@RequestBody和@RequestParam,java,spring,spring-mvc,Java,Spring,Spring Mvc,我正在编辑一个使用Spring的web项目,我需要添加一些Spring的注释。我要添加的两个是和。我已经摸索了一下,发现了一些问题,但我仍然不完全理解如何使用这些注释。有人能举个例子吗?控制器示例: @Controller class FooController { @RequestMapping("...") void bar(@RequestBody String body, @RequestParam("baz") baz) { //method body
@Controller
class FooController {
@RequestMapping("...")
void bar(@RequestBody String body, @RequestParam("baz") baz) {
//method body
}
}
:变量体将包含HTTP请求的主体
:变量baz将保存请求参数baz的值@RequestParam注释参数链接到特定的Servlet请求参数。参数值将转换为声明的方法参数类型。 此注释指示方法参数应绑定到web请求参数 例如,Spring RequestParam的角度请求如下所示:
$http.post('http://localhost:7777/scan/l/register“,{params:{“username”:$scope.username,“password”:$scope.password,“auth”:true})。
成功(函数(数据、状态、标题、配置){
...
})
@RequestMapping(method=RequestMethod.POST,products=“application/json”,value=“/register”)
公共地图登记册(uiModel),
@RequestParam字符串用户名、@RequestParam字符串密码、布尔身份验证、,
HttpServletRequest HttpServletRequest){。。。
@RequestBody注释参数链接到HTTP请求正文。参数值使用HttpMessageConverters转换为声明的方法参数类型。
此注释指示应将方法参数绑定到web请求的主体
例如,Spring RequestBody的角度请求如下所示:
$scope.user={
用户名:“foo”,
作者:是的,
密码:“bar”
};
$http.post('http://localhost:7777/scan/l/register“,$scope.user)。
成功(函数(数据、状态、标题、配置){
...
})
@RequestMapping(method=RequestMethod.POST,products=“application/json”,value=“/register”)
公共地图登记册(uiModel),
@请求主体用户,
HttpServletRequest HttpServletRequest){。。。
希望这有帮助。一个方法可以有多个@RequestBody参数吗?不可以,因为只有一个HTTP正文,所以只能有一个RequestBody变量文档中有很好的示例,用于和
$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) {...
$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) {...