Jersey(1.19.1) - Root Resource Classes
Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least one method annotated with @Path or a resource method designator annotation such as @GET, @PUT, @POST, @DELETE. Resource methods are methods of a resource class annotated with a resource method designator. This section shows how to use Jersey to annotate Java objects to create RESTful web services.
The following code example is a very simple example of a root resource class using JAX-RS annotations.
package com.sun.ws.rest.samples.helloworld.resources; import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path; // The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorld { // The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media type "text/plain"
@Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";
}
}
Let's look at some of the JAX-RS annotations used in this example.
@Path
The @Path annotation's value is a relative URI path. In the example above, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation. What makes JAX-RS so useful is that you can embed variables in the URIs.
URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by curly braces. For example, look at the following @Path annotation:
@Path("/users/{username}")
In this type of example, a user will be prompted to enter their name, and then a Jersey web service configured to respond to requests to this URI path template will respond. For example, if the user entered their username as "Galileo", the web service will respond to the following URL:
http://example.com/users/Galileo
To obtain the value of the username variable the @PathParam may be used on method parameter of a request method, for example:
@Path("/users/{username}")
public class UserResource { @GET
@Produces("text/xml")
public String getUser(@PathParam("username") String userName) {
...
}
}
If it is required that a user name must only consist of lower and upper case numeric characters then it is possible to declare a particular regular expression, which overrides the default regular expression, "[^/]+?", for example:
@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
In this type of example the username variable will only match user names that begin with one upper or lower case letter and zero or more alpha numeric characters and the underscore character. If a user name does not match that a 404 (Not Found) response will occur.
A @Path value may or may not begin with a '/', it makes no difference. Likewise, by default, a @Path value may or may not end in a '/', it makes no difference, and thus request URLs that end or do not end in a '/' will both be matched. However, Jersey has a redirection mechanism, which if enabled, automatically performs redirection to a request URL ending in a '/' if a request URL does not end in a '/' and the matching @Path does end in a '/'.
HTTP Methods
@GET, @PUT, @POST, @DELETE and @HEAD are resource method designator annotations defined by JAX-RS and which correspond to the similarly named HTTP methods. In the example above, the annotated Java method will process HTTP GET requests. The behavior of a resource is determined by which of the HTTP methods the resource is responding to.
The following example is an extract from the storage service sample that shows the use of the PUT method to create or update a storage container:
@PUT
public Response putContainer() {
System.out.println("PUT CONTAINER " + container); URI uri = uriInfo.getAbsolutePath();
Container c = new Container(container, uri.toString()); Response r;
if (!MemoryStore.MS.hasContainer(c)) {
r = Response.created(uri).build();
} else {
r = Response.noContent().build();
} MemoryStore.MS.createContainer(c);
return r;
}
By default the JAX-RS runtime will automatically support the methods HEAD and OPTIONS, if not explicitly implemented. For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). For OPTIONS the Allow response header will be set to the set of HTTP methods support by the resource. In addition Jersey will return a WADL document describing the resource.
@Produces
The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client. In this example, the Java method will produce representations identified by the MIME media type "text/plain".
@Produces can be applied at both the class and method levels. Here's an example:
@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
@GET
public String doGetAsPlainText() {
...
} @GET
@Produces("text/html")
public String doGetAsHtml() {
...
}
}
The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. The doGetAsHtml method's @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text.
If a resource class is capable of producing more that one MIME media type then the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically the Accept header of the HTTP request declared what is most acceptable. For example if the Accept header is:
Accept: text/plain
then the doGetAsPlainText
method will be invoked. Alternatively if the Accept header is:
Accept: text/plain;q=0.9, text/html
which declares that the client can accept media types of "text/plain" and "text/html" but prefers the latter, then the doGetAsHtml method will be invoked.
More than one media type may be declared in the same @Produces declaration, for example:
@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}
The doGetAsXmlOrJson
method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.
The examples above refer explicitly to MIME media types for clarity. It is possible to refer to constant values, which may reduce typographical errors, see the constant field values of MediaType.
@Consumes
The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. The above example can be modified to set the cliched message as follows:
@POST
@Consumes("text/plain")
public void postClichedMessage(String message) {
// Store the message
}
In this example, the Java method will consume representations identified by the MIME media type "text/plain". Notice that the resource method returns void. This means no representation is returned and response with a status code of 204 (No Content) will be returned.
@Consumes can be applied at both the class and method levels and more than one media type may be declared in the same @Consumes declaration.
Jersey(1.19.1) - Root Resource Classes的更多相关文章
- Jersey(1.19.1) - Life-cycle of Root Resource Classes
By default the life-cycle of root resource classes is per-request, namely that a new instance of a r ...
- 九月 26, 2017 10:18:14 上午 com.sun.jersey.server.impl.application.RootResourceUriRules <init> 严重: The ResourceConfig instance does not contain any root resource classes.
Tomcat启动错误:九月 26, 2017 10:18:14 上午 com.sun.jersey.server.impl.application.RootResourceUriRules <i ...
- Root resource classes
Overview A root resource class is the entry point into a JAX-RS implemented RESTful Web service. It ...
- The ResourceConfig instance does not contain any root resource classes
问题描述 当我们在使用 myeclipse 创建 Web Service Projects 项目后,运行项目然后就会出现这个问题. 解决方案 通过这个错误描述,我们项目没有找到这个资源.报错的原因在于 ...
- Jersey(1.19.1) - Hello World, Get started with Jersey using the embedded Grizzly server
Maven Dependencies The following Maven dependencies need to be added to the pom: <dependency> ...
- Jersey(1.19.1) - Sub-resources
@Path may be used on classes and such classes are referred to as root resource classes. @Path may al ...
- Jersey(1.19.1) - Deploying a RESTful Web Service
JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and pro ...
- Jersey(1.19.1) - Building URIs
A very important aspects of REST is hyperlinks, URIs, in representations that clients can use to tra ...
- Jersey(1.19.1) - Conditional GETs and Returning 304 (Not Modified) Responses
Conditional GETs are a great way to reduce bandwidth, and potentially server-side performance, depen ...
随机推荐
- 设计模式-结合Android代码
开始学设计模式 1 单例模式 单例模式可以说是最容易理解的模式了,也是应用最广的模式之一,先看看定义吧. 定义:确保单例类只有一个实例,并且这个单例类提供一个函数接口让其他类获取到这个唯一的实例. 什 ...
- 在DWZ框架中整合kindeditor复文本框控件
今天上午在DWZ框架中整合kindeditor复文本框控件,发现上传图片是老是提示 “上传中,请稍候...”,上网查看别人说可能是文件路径问题,在想以前在其他项目中用这个控件一直没问题,到这里怎么会出 ...
- QM课程02-外部功能
质量计划 · 对质量计划和检验计划进行基本数据的管理 · 物料说明 · 检验计划 质量检验 · 触发检验 · 具有检验计划选择和样本计算的检验处理 · 打印采样和检验的车间文档 · 记录结果和缺陷 · ...
- Codeforces Round #332 (Div. 2) C. Day at the Beach 线段树
C. Day at the Beach Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/599/p ...
- Codeforces Gym 100425H H - Football Bets 构造
H - Football BetsTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/ ...
- 从零开始学习Hadoop--前言
Hadoop是最著名使用最广泛的分布式大数据处理框架,它是用Java开发的. 这本书有一个明确的目标:只要有一台能上网的计算机,就可以让读者在最短的时间内,学会Hadoop的初级开发.所以,这本书只讲 ...
- webqq 获得好友列表hash算法 获得最新hash的方法
webqq获得好友列表的hash算法,大约每一个月中旬会变动一次.知道怎么获得他就能够了. js文件路径 http://web.qstatic.com/webqqpic/pubapps/0/50/eq ...
- ElasticSearch使用
安装之前,请参考https://github.com/richardwilly98/elasticsearch-river-mongodb根据你的MongoDB版本号决定需要的elasticsearc ...
- 通过tracing技术来教授操作系统
https://www.cl.cam.ac.uk/teaching/1516/L41/materials.html https://github.com/myaut/dtrace-stap-book
- maven插件开发(二)
因为很多jar都是在开发环境中,没有到仓库中,因此偷个懒,用命令直接自动安装到仓库去.在开发的过程中遇到一个比较诡异的问题,插件用命令调mvn 安装jar到仓库总是抛如下异常: maven Canno ...