这几天做东西接触了JAX-RS的东西,没有系统的从开始就学,只是单纯去复制粘贴的用,主要用到了几个Annotations变量,具体如下:

queryparam、PathParam、FormParam、Context、RestController。下面就分别解释下他们的用法:

1.@queryparam

Path("/users")
public class UserService { @GET
@Path("/query")
public Response getUsers(
@QueryParam("from") int from,
@QueryParam("to") int to,
@QueryParam("orderBy") List<String> orderBy) { return Response
.status(200)
.entity("getUsers is called, from : " + from + ", to : " + to
+ ", orderBy" + orderBy.toString()).build(); } }

这里,在url中输入"/users/query/from=1&to=100&orderBy=name&orderBy=age",则输出一下结果:

getUsers is called, from : 1, to : 100, orderBy[name, age]

这里,也可以以动态方式获得,如下:

@Path("/users")
public class UserService { @GET
@Path("/query")
public Response getUsers(@Context UriInfo info) { String from = info.getQueryParameters().getFirst("from");
String to = info.getQueryParameters().getFirst("to");
List<String> orderBy = info.getQueryParameters().get("orderBy"); return Response
.status(200)
.entity("getUsers is called, from : " + from + ", to : " + to
+ ", orderBy" + orderBy.toString()).build(); }

URL:users/query?from=100&to=200&orderBy=age&orderBy=name 
输出为: 
getUsers is called, from : 100, to : 200, orderBy[age, name] 
注意这里把orderby后的两个参数读入为LIST处理了.

2.@pathParam

与@queryParam类似,但是,queryparam在url中是用键值对来传递,而在pathParam中是只出现值而不出现参数,

url如是:"/users/2011/20/10",例如:

@GET
@Path("{year}/{month}/{day}")
public Response getUserHistory(
@PathParam("year") int year,
@PathParam("month") int month,
@PathParam("day") int day) { String date = year + "/" + month + "/" + day; return Response.status(200)
.entity("getUserHistory is called, year/month/day : " + date)
.build(); }

这里通过上面的url将输出:

  getUserHistory is called, year/month/day : 2011/20/10

可以用多个param,并且若path中有相同参数名,则采用最接近的参数名所对应的值,如

@Path("/customers/{id}")
public class CustomerResource {
@Path("/address/{id}")
@Produces("text/plain")
@GET
public String getAddress(@PathParam("id") String addressId) {...}
}

如:customers/123/address/456 , 则 addressId 的值为456.

3.@DefaultValue

@Path("/users")
public class UserService { @GET
@Path("/query")
public Response getUsers(
@DefaultValue("1000") @QueryParam("from") int from,
@DefaultValue("999")@QueryParam("to") int to,
@DefaultValue("name") @QueryParam("orderBy") List<String> orderBy) { return Response
.status(200)
.entity("getUsers is called, from : " + from + ", to : " + to
+ ", orderBy" + orderBy.toString()).build(); }

输入url为:/users/query

输出为:

getUsers is called, from : 1000, to : 999, orderBy[name]

4.@FormParam

FormParam用于提取post请求中的form数据,具体举例如下:

<FORM action="http://example.com/customers" method="post">
<P>
First name: <INPUT type="text" name="firstname"><BR>
Last name: <INPUT type="text" name="lastname"><BR>
<INPUT type="submit" value="Send">
</P>
</FORM>
@Path("/customers")
public class CustomerResource {
@POST
public void createCustomer(@FormParam("firstname") String first,
@FormParam("lastname") String last) {
...
}
}

5.@context

当jax-rs服务基于servlet发布的时候 ,还可以通过@Context注入servlet中的ServletConfig , ServletContext ,HttpServletRequest , HttpServletResponse

然后REST就可以通过sessionid来保持住用户状态。举例如下:

@Path("UserContext")
public class UserContext { @Context UriInfo uriInfo;
@Context HttpHeaders httpHeaders;
@Context SecurityContext sc;
@Context Request req;
@Context Response resp;
@Context HttpServletResponse response;
@Context HttpServletRequest request; @GET
public String hi(@QueryParam("name") String yourName ){
if(yourName!=null)
request.getSession().setAttribute("name", yourName); String username = (String) request.getSession().getAttribute("name");
if(username!=null){
System.out.println(request.getSession().getId() + ":" + username);
}
else{
System.out.println(request.getSession().getId() + "没有用户");
}
return null;
}
}
<!--在web.xml加入-->
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>

在url中输入:”/rest/services/UserContext“则输出:

A46756539D2E39CC2CFFCB3FE1C99E70没有用户

若在url中输入:http://localhost:8080/rest/services/UserContext?name=hello

则输出:

A46756539D2E39CC2CFFCB3FE1C99E70:hello

6.@RestController

它继承自@Controller注解,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController

定义如下:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController

7.还有cookieparam和headerparam等,此处没怎么接触,就先不学习了。

JAX-RS之queryparam、PathParam、DefaultValue、FormParam、Context、RestController等的更多相关文章

  1. jax-rs中的一些参数标注简介(@PathParam,@QueryParam,@MatrixParam,@HeaderParam,@FormParam,@CookieParam)

    先复习一下url的组成: scheme:[//[user:password@]host[:port]][/]path[?query][#fragment] jax-rs anotation @Path ...

  2. [REST Jersey] @QueryParam Demo

    This demo sourced from the jersey tutor. https://jersey.java.net/documentation/latest/jaxrs-resource ...

  3. React 新 Context API 在前端状态管理的实践

    本文转载至:今日头条技术博客 众所周知,React的单向数据流模式导致状态只能一级一级的由父组件传递到子组件,在大中型应用中较为繁琐不好管理,通常我们需要使用Redux来帮助我们进行管理,然而随着Re ...

  4. React 全新的 Context API

    Context API 可以说是 React 中最有趣的一个特性了.一方面很多流行的框架(例如react-redux.mobx-react.react-router等)都在使用它:另一方面官方文档中却 ...

  5. Apache CXF 3.0: CDI 1.1 Support as Alternative to Spring--reference

    With Apache CXF 3.0 just being released a couple of weeks ago, the project makes yet another importa ...

  6. REST 在 Java 中的使用

    REST是一种混合的架构风格,它的由来以及它的架构元素在笔者的前一篇文章<REST 架构风格的由来 & 元素>中已经描述了.本篇主要描述一下J2EE对REST的支持. Java是在 ...

  7. Jersey MVC

    Jersey是JAX-RS(JavaAPI for RESTful Service)标准的一个实现,用于开发RESTful Web Application.可以参考JAX-RS的介绍(http://w ...

  8. Spring boot中使用springfox来生成Swagger Specification小结

    Rest接口对应Swagger Specification路径获取办法: 根据location的值获取api   json描述文件 也许有同学会问,为什么搞的这么麻烦,api json描述文件不就是h ...

  9. RestEasy简介

    RestEasy简介 RestEasy技术说明 简介 RESTEasy RESTEasy是JBoss的一个开源项目,提供各种框架帮助你构建RESTful Web Services和RESTful Ja ...

随机推荐

  1. 初识 Zookeeper

    云计算越来越流行的今天,单一机器处理能力已经不能满足我们的需求,不得不采用大量的服务集群.服务集群对外提供服务的过程中,有很多的配置需要随时更新,服务间需要协调工作,这些信息如何推送到各个节点?并且保 ...

  2. 《大型网站系统与JAVA中间件实践》读书笔记-消息中间件

    消息中间件 1.消息中间件的价值 1.1 透过示例看消息中间件对应用的解耦 1.1.1.通过服务调用让其他系统感知事件发生的方式 假设我们要做一个用户登录系统,其中需要支持的一个功能是,用户登录成功 ...

  3. LeetCode——Reverse String

    LeetCode--Reverse String Question Write a function that takes a string as input and returns the stri ...

  4. java用servlet、cookie实现一个阅读记录

    效果如图 代码1 package com.xiaostudy.servlet; import java.io.IOException; import java.io.PrintWriter; impo ...

  5. Pandas注意事项&窍门

    警告和疑难意味着一个看不见的问题.在使用Pandas过程中,需要特别注意的地方. 与Pandas一起使用If/Truth语句 当尝试将某些东西转换成布尔值时,Pandas遵循了一个错误的惯例. 这种情 ...

  6. activity状态的保存和恢复

    activity状态的保存和恢复 一.简介 1.保存activity状态 * 保存activity状态,onSaveInstanceState这个方法会自动保存有ID的组件的状态 * 没有ID的组件或 ...

  7. 地图Legend控件的使用

    http://support.esrichina-bj.cn/2011/0318/1150.html

  8. hdu2586倍增lca

    求距离 #include<map> #include<set> #include<cmath> #include<queue> #include< ...

  9. sql server数据库课程设计分析

    课题:能源管理收费系统 系统功能的基本要求: (1)用户基本信息的录入:包括用户的单位.部门.姓名.联系电话.住址 : (2)用户水.电.气数据的录入(每个月的数据的录入): (3)水.电.气价格的管 ...

  10. LeetCode OJ:Linked List Cycle II(循环链表II)

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Note ...