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的更多相关文章

  1. 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 ...

  2. 九月 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 ...

  3. Root resource classes

    Overview A root resource class is the entry point into a JAX-RS implemented RESTful Web service. It ...

  4. The ResourceConfig instance does not contain any root resource classes

    问题描述 当我们在使用 myeclipse 创建 Web Service Projects 项目后,运行项目然后就会出现这个问题. 解决方案 通过这个错误描述,我们项目没有找到这个资源.报错的原因在于 ...

  5. 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> ...

  6. 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 ...

  7. Jersey(1.19.1) - Deploying a RESTful Web Service

    JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and pro ...

  8. Jersey(1.19.1) - Building URIs

    A very important aspects of REST is hyperlinks, URIs, in representations that clients can use to tra ...

  9. 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 ...

随机推荐

  1. [HDU 4089]Activation[概率DP]

    题意: 有n个人排队等着在官网上激活游戏.Tomato排在第m个. 对于队列中的第一个人.有以下情况: 1.激活失败,留在队列中等待下一次激活(概率为p1) 2.失去连接,出队列,然后排在队列的最后( ...

  2. springMVC部署

      一.导入springMVC所需要的jar包   下载地址:http://repo.spring.io/release/org/springframework/spring/   二.springM ...

  3. iOS 判断只有数字、小数点和减号

    #define NUMBERS @"0123456789.-" //数字 #define NUM @"0123456789" //字母 #define ALPH ...

  4. Codeforces Round #332 (Div. 2) B. Spongebob and Joke 水题

    B. Spongebob and Joke Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/599 ...

  5. BZOJ 2748: [HAOI2012]音量调节 dp

    2748: [HAOI2012]音量调节 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/p ...

  6. Codeforces Round #331 (Div. 2)C. Wilbur and Points 贪心

    C. Wilbur and Points Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/596/ ...

  7. [AngularJS] Test an Angular Component with $componentController

    Traditionally you had to create DOM elements to test a directive but by shifting our focus to compon ...

  8. [MEAN Stack] First API -- 4. Organize app structure

    The app structure: Front-end: app.js /** * Created by Answer1215 on 12/9/2014. */ 'use strict'; func ...

  9. Android实现图表绘制和展示

    本文演示在Android平台中绘制和展示图表示例,本示例是基于RChart 2实现的. 在一个系统中经常要用到图表统计数据,在WEB开发中图表绘制是一件简单的事情,因为有比较多的开源方案.但在Andr ...

  10. iOS开发——语法篇OC篇&静态方法与实例方法

    静态方法与实例方法 方法是类的行为,写在接口和实现两个文件中.在接口部分声明方法,在实现部分实现方法. 1.类方法与实例方法 Objective-C中的类可以声明两种类型的方法:实例方法和类方法.实例 ...