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 ...
随机推荐
- 转载 C#结构体(struct)和类(class)的区别
转载原地址: http://dotnet.9sssd.com/csbase/art/8 C#结构体和类的区别问题:在C#编程语言中,类属于引用类型的数据类型,结构体属于值类型的数据类型,这两种数据类型 ...
- Educational Codeforces Round 13 D. Iterated Linear Function (矩阵快速幂)
题目链接:http://codeforces.com/problemset/problem/678/D 简单的矩阵快速幂模版题 矩阵是这样的: #include <bits/stdc++.h&g ...
- quartz源码解析(一)
本文的起因源于一次quartz的异常,在win2003正常运行的程序放在linux环境就抛出异常了,虽然找出异常没花我多长时间,不过由此加深了对quzrtz的了解:古人说,三折肱,为良医,说明经验对于 ...
- MATLAB代码
clear;clc%%%%%%%%%%%%方程里的参量%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%alpha=0.5;beta=0.5;%%% ...
- python的random模块
As an example of subclassing, the random module provides the WichmannHill class that implements an a ...
- Java中字符串相等与大小比较
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...
- 有关java中static关键的重写问题
<Java编程思想>中这样提到“只有普通的方法调用可以是多态的”.说白了,就是静态方法不能实现重写这种多态. JAVA静态方法形式上可以重写(只要子类不加@Override关键字修饰的话, ...
- Educational Codeforces Round 1 A. Tricky Sum 暴力
A. Tricky Sum Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/598/problem ...
- C++ Button右键弹出式菜单
Button右键弹出式菜单 关键点 用类来实现 的 实现过程 新建1个类 类名CButtonPopMenu 基类CButton 新建1个菜单资源 IDR_MENU1 // ButtonPopMenu ...
- 理解WebKit和Chromium: 调试Android系统上的Chromium
转载请注明原文地址:http://blog.csdn.net/milado_nju 1. Android上的调试技术 在Android系统上,开发人员能够使用两种不同的语言来开发应用程序,一种是Jav ...