今天用jersey写接口,发现有一个post方法中没有得到参数,查了半天发现自己一不小心将@formparam写成了@queryparam,真是一个悲伤的故事。在这里把几个参数类型整理了一下放出来。
1.
@PathParam
使用@PathParam可以获取URI中指定规则的参数,举个例子:
类中@Path("/user")
@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
...
}
当浏览器请求http://localhost/user/jack时,userName值为jack。
注意,这里的username并不是说Key是username, value是jack而是说/usr/后面跟着的东西就是username,这里username只是个变量
2.
@QueryParam
@QueryParam用于获取GET请求中的查询参数,如:
@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
@QueryParam("age") int age) {
...
}
当浏览器请求http://host:port/user?name=rose&age=25时,name值为rose,age值为25。如果需要为参数设置默认值,可以使用
3.
@DefaultValue,如:
@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
@DefaultValue("26") @QueryParam("age") int age) {
...
}
当浏览器请求http://host:port/user?name=rose时,name值为rose,age值为26。
4.
@FormParam
@FormParam,顾名思义,从POST请求的表单参数中获取数据。如:
@POST
@Consumes("application/x-www-form-urlencoded")
publicvoid post(@FormParam("name") String name) {
// Store the message
}
相信使用过html进行post提交的人对表单一定不陌生,可以想象成这就是在模拟html中表单的请求。
5.
使用Map
在一个大型的server中,因为参数的多变,参数结构的调整都会因为以上几种方式而遇到问题,这时可以考虑使用@Context 注释,并获取UriInfo实例,如下:
@GET
public String get(@Context UriInfo ui) {
MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}
我觉得,可以认为map是上面几种情况的超集,因为它能够替代以上任意一种。map就是context
同样还可以通过@Context 注释获取ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等,如下:
@Path("/")
publicclass Resource {
@Context
HttpServletRequest req;
@Context
ServletConfig servletConfig;
@Context
ServletContext servletContext;
@GET
public String get(@Context HttpHeaders hh) {
MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
Map<String, Cookie> pathParams = hh.getCookies();
}
}
分享到:
相关推荐
restful接口示例代码restful接口示例代码restful接口示例代码restful接口示例代码
RESTFUL接口文档模板,样式好看的接口文档模板,docx格式
开发restful接口应该遵循统一的规范,保持规范的统一才能方便维护和应用
jersey构建简单的Restful服务!
使用python的第三方库编码写restful接口,easy
NC65通过自带的rest文件检索restful接口,实现对外开放的restful接口,使用方式和其他web系统的使用方法一致,只是规范了访问链接格式
CAS restFul 接口调用 获取票据
SpringBoot+jpa Restful接口 无配置,最简单实现 jpa增删改差实现Restful 接口返回数据
最近在搞springboot的模块化开发,集成了shiro+jwt实现restful接口的token认证。 需新增测试表: CREATE TABLE `t_user` ( `user_id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT, `user_name` varchar(32...
这是一个restful风格的webservice框架,使用官方的jersey 整合mybatis和spring,需要用tomcat8才能运行,
接口测试demo,用来测试restful接口,输入参数就可以测试接口测试demo,用来测试restful接口,输入参数就可以测试
采用spring 结合cxf 发布一个RestFul接口。 http请求,soap均可调用。
使用SpringBoot整合jersey 实现Restful web service.同时整合springmvc。
Spring Hibernate, Jersey 创建restful 服务的例子 图文并茂,step by step
Thingworx获取Restful接口的方法;详细的代码使用案列,对初入Thingworx平台的朋友一定有帮助
jersey的使用简单实例
Insomnia restful接口调试工具,官网下载慢,特放到这里方便大家使用,restful client
jersey RESTful service 源代码 jersey RESTful service 源代码
这是我公司使用的REST标准,具有一定的参考性。