主要围绕如下请求方式:
@requestparam、@pathvariable、@matrixvariable、@requestbody、@requestheader和@cookievalue的基本知识、详细分析以及示例
1. @requestparam
用于绑定http请求参数到控制器方法的参数上,常用于处理表单数据或查询参数
@getmapping("/greeting")
public string greeting(@requestparam(name="name", required=false, defaultvalue="world") string name) {
return "hello, " + name;
}
基本的属性如下:
- value 或 name: 参数名
- required: 是否为必需参数,默认为true
- defaultvalue: 参数的默认值
具体调用两种方式:
/greeting?name=john,输出hello, john/greeting,输出默认值 hello, world
2. @pathvariable
用于绑定url中的模板变量到控制器方法的参数上,常用于restful风格的url路径中
@getmapping("/users/{id}")
public user getuser(@pathvariable("id") long id) {
return userservice.findbyid(id);
}
基本的属性如下:
- value 或 name: 路径变量名。
- required: 是否为必需参数,默认为true
请求方式: /users/1,用户id为1的用户对象
3. @matrixvariable
用于绑定url路径中的矩阵变量到控制器方法的参数上,需要在spring mvc中启用矩阵变量支持
常与路径变量结合使用
@getmapping("/owners/{ownerid}/pets/{petid}")
public pet findpet(@pathvariable string ownerid,
@matrixvariable(name="q", pathvar="petid") int query) {
// 处理代码
}
基本的属性如下:
- value 或 name: 矩阵变量名
- pathvar: 矩阵变量所属的路径变量名
具体调用方式如下:/owners/42/pets/21;q=123,提取: ownerid 为42, petid 为21, q 为123
4. @requestbody
用于将http请求体的内容绑定到控制器方法的参数上,常用于处理json、xml等格式的请求数据
@postmapping("/users")
public user createuser(@requestbody user user) {
return userservice.save(user);
}
- required: 是否为必需参数,默认为true
具体调用方式如下:
http post请求,内容: {“name”: “john”, “age”: 30}
返回: 创建的用户对象
5. @requestheader
用于绑定http请求头到控制器方法的参数上
@getmapping("/header")
public string getheader(@requestheader("user-agent") string useragent) {
return "user-agent: " + useragent;
}
- value 或 name: 请求头名
- required: 是否为必需参数,默认为true
- defaultvalue: 参数的默认值
具体调用方式如下:
设置请求头user-agent
返回: 用户代理信息
6. @cookievalue
用于绑定http请求的cookie值到控制器方法的参数上
@getmapping("/cookie")
public string getcookie(@cookievalue(value = "sessionid", defaultvalue = "defaultsessionid") string sessionid) {
return "session id: " + sessionid;
}
具体的属性如下:
- value 或 name: cookie名
- required: 是否为必需参数,默认为true
- defaultvalue: 参数的默认值
具体调用方式如下:
设置cookie sessionid
返回: 会话id信息
7. 总结
| 注解 | 作用 | 属性 | 示例调用 |
|---|---|---|---|
| @requestparam | 绑定http请求参数到控制器方法的参数上 | value, required, defaultvalue | /greeting?name=john |
| @pathvariable | 绑定url中的模板变量到控制器方法的参数上 | value, required | /users/1 |
| @matrixvariable | 绑定url路径中的矩阵变量到控制器方法的参数上 | value, pathvar | /owners/42/pets/21;q=123 |
| @requestbody | 将http请求体的内容绑定到控制器方法的参数上 | required | http post 请求,内容: {“name”: “john”} |
| @requestheader | 绑定http请求头到控制器方法的参数上 | value, required, defaultvalue | 设置请求头user-agent |
| @cookievalue | 绑定http请求的cookie值到控制器方法的参数上 | value, required, defaultvalue | 设置cookie sessionid |
以上就是java中的6种请求方式的示例详解的详细内容,更多关于java请求方式的资料请关注代码网其它相关文章!
发表评论