@reqeustBody
- 常用来处理content-type==不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,当然,也可 以将其分别绑定到对应的字符串上。
- 在Get请求中,没有HttpEntity,所以@RequestBody并不适用
- 在Post请求中,因为必须在请求头中申明Content-Type,则可以使用
public void login(@requestBody String userName,@requestBody String pwd){
System.out.println(userName+" :"+pwd);
}
假如我有一个User类,拥有如下字段:
public class User {
String userName;
String pwd;
}
那么上述参数可以改为以下形式
public void login(@requestBody User user){
}
这种形式会将JSON字符串中的值赋予user中对应的属性上
注意:JSON字符串中的key必须对应user中的属性名,否则是请求不过去的
@RequestParam
- 请求处理的方法的参数的类型为Java基本类型和String.也可以接受对象类型
- 常用来处理content-type为默认的application/x-www-form-urlcoded编码
属性 | 类型 | 是否必要 | 说明 |
---|---|---|---|
name | String | 否 | 指定请求参数绑定的名称 |
value | String | 否 | name属性的别名 |
required | boolean | 否 | 指定参数是否必须绑定 |
default | String | 否 | 没有参数时使用的默认值 |
@PathVariable
- 只支持一个类型为String的属性,表示绑定的请求参数的名称,省略则默认绑定同名的参数。
- 通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx”) 绑定到操作方法的入参中。
String edit(@PathVariable("orwModelid") String orwModelid,Model model){
DataMastDO dataMast = dataMastService.get(orwModelid);
model.addAttribute("dataMast", dataMast);
return "system/dataMast/edit";
}
/**
* localhost:8080/springmvc/hello/pathVariable/bigsea
* localhost:8080/springmvc/hello/pathVariable/sea
* 这些URL 都会 执行此方法 并且将 <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段
* @param name
* @return
*/
@RequestMapping("/pathVariable/{name}")
public String pathVariable(@PathVariable("name")String name){
System.out.println("hello "+name);
return "helloworld";
}
---------------------
作者:胡小海丶
来源:CSDN
原文:https://blog.csdn.net/a67474506/article/details/46361195
版权声明:本文为博主原创文章,转载请附上博文链接!
什么都不写,直接写参数
- springmvc会自动根据参数名字来注入,所以要名字一致,不然不会注入
总结
- @RequestBody @RequstParam @PathVariable
- 在判断适用哪一个时,如下:
$.ajax({
url:prefix + '/getUser',
// 数据发送方式
type: "post",
// 接受数据格式
dataType:"json",
contentType: "application/json;charset=utf-8",
// 要传递的数据
data:JSON.stringify({'name':'a'}),
// 回调函数,接受服务器端返回给客户端的值,即result值
success:function(jsons){
}
})
- Post
- 判断contentType,是"application/json;charset=utf-8", 使用@ReuqestBody
- 判断contentType,是“application/xml”,使用@RequestBody
- 判断contentType,是“application/x-www-form-urlcoded”,使用@RequestParam
- Get
- 使用 @PathVariable