Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Jersey strategy for building RESTful Web services in JAX-RS

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

JAX-RS Jersey building RESTful Web service strategy is like, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Introduction to RESTful Web Servic

REST was proposed in 2000 in his doctoral thesis by Roy Fielding, one of the lead authors of the HTTP specification version 1.0 and 1.1.

The most important concept in REST is resources, which is identified by a global ID (usually URI). Client applications use the HTTP method (GET/ POST/ PUT/ DELETE) to manipulate resources or resource sets. RESTful Web service is a Web service implemented using HTTP and REST principles. In general, a RESTful Web service should define the following:

The base / root URI of the Web service, such as http://host//resources.

Support response data of type MIME, including JSON/XML/ATOM, and so on.

A collection of operations supported by the service (for example, POST, GET, PUT, or DELETE).

Table 1 illustrates the resource URI and HTTP methods used in a typical RESTful Web service.

Table 1. RESTful Web service example

Method / resource resource collection, such as URI:

Http://host//resources

Member resources, such as URI:

Http://host//resources/1234

GET lists all members of the resource collection. Retrieves the representation of the resource identified as 1234. PUT updates (replaces) another collection with one collection. Update the digital resource labeled 1234. POST creates digital resources in the collection, and its ID is automatically allocated. Create a child resource below. DELETE deletes the entire resource collection. Delete the digital resource marked 1234.

JSR 311 (JAX-RS) and Jersey

The proposal for JSR 311 or JAX-RS (Java API for RESTful Web Services) began in 2007 and was finalized from version 1.0 to October 2008. At present, JSR 311 version 1.1 is still in the draft stage. The purpose of this JSR is to provide a set of API to simplify the development of REST-style Web services.

Before the JAX-RS specification, there were frameworks such as Restlet and RestEasy that could help you implement RESTful Web services, but they were not intuitive enough. Jersey is the reference implementation of JAX-RS, which consists of three main parts.

Core server (Core Server): by providing standardized annotations and API standardization in JSR 311, you can develop RESTful Web services in an intuitive way.

Core client (Core Client): the Jersey client API helps you communicate with REST services easily.

Integration: Jersey also provides libraries that can easily integrate Spring, Guice, and Apache Abdera.

In the following parts of this article, I introduced all of these components, but focused more on the core server.

Build a RESTful Web service

I'll start with a "hello world" application that can be integrated into Tomcat. This application will walk you through the process of setting up the environment and involve the basics of Jersey and JAX-RS.

Then I'll introduce more complex applications and delve into the nature and features of JAX-RS, such as support for multiple MIME type representations, JAXB support, and so on. I'll take some code snippets from the sample to introduce important concepts.

Hello World: the first Jersey Web project

To set up the development environment, you need the following:

IDE:Eclipse IDE for JEE (v3.4 +) or IBM Rational Application Developer 7.5

Java SE5 or later

Web container: Apache Tomcat 6. 0 (Jetty and others are also available)

Jersey library: Jersey 1.0.3 archive, containing all necessary libraries

Set up the environment for Jersey

First, create a server runtime for Tomcat 6. 0 on Eclipse. This is the Web container for RESTful Web applications. Then create an application called "Jersey" and specify the target runtime as Tomcat 6. 0.

Finally, copy the following libraries from the Jersey package to the library directory under WEB-INF:

Core server: jersey-core.jar,jersey-server.jar,jsr311-api.jar,asm.jar

Core client: (for testing) jersey-client.jar

JAXB support: (used in advanced samples) jaxb-impl.jar,jaxb-api.jar,activation.jar,stax-api.jar,wstx-asl.jar

JSON support: (used in advanced samples) jersey-json.jar

Develop REST services

You have now set up the environment for developing the first REST service, which issues a "Hello" to the client.

To do this, you need to send all REST requests to the Jersey container-- defining the servlet scheduler in the application's web.xml file (see listing 1). In addition to declaring Jersey servlet, it defines an initialization parameter that indicates the Java package that contains the resource.

Listing 1. Define the Jersey servlet scheduling level in the web.xml file

Jersey REST Service com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages sample.hello.resources 1 Jersey REST Service / rest/*

Now you will write a resource called HelloResource that accepts HTTP GET and responds to "Hello Jersey".

Listing 2. HelloResource in the sample.hello.resources package

@ Path ("/ hello") public class HelloResource {@ GET@Produces (MediaType.TEXT_PLAIN) public String sayHello () {return "Hello Jersey";}}

There are several areas in this code that need to be emphasized:

Resource class (Resource Class): note that the resource class is a simple Java object (POJO) that can implement any interface. This adds many benefits, such as reusability and simplicity.

Annotation: defined in javax.ws.rs.* as part of the JAX-RS (JSR 311) specification.

@ Path: define the resource base URI. It consists of a context root and a host name, and the resource identifier is similar to http://localhost:8080/Jersey/rest/hello.

GET: this means that the following methods can respond to the HTTP GET method.

Produces: defines the response content MIME type in plain text.

Test the Hello application

To test the application, open your browser and type URL http://://rest/hello. You will see the response "Hello Jersey". This is very simple, using comments to handle requests, responses, and methods.

The following sections cover the necessary parts of the JAX-RS specification, using code snippets from the Contacts sample application. You can find all the code for this high-level sample in the source code package.

Resources

Resources are a key part of a RESTful Web service. You can manipulate resources using HTTP methods such as GET, POST, PUT, and DELETE. Everything in the application is a resource: employees, contacts, organizations, and so on. In JAX-RX, resources are implemented through POJO, using @ Path annotations to form their identifiers. Resources can have child resources. In this case, the parent resource is the resource collection and the child resource is the member resource.

In the sample Contacts application, you will manipulate personal contacts and contact collections. ContactsResource is a collection resource of / contacts URI, and ContactResource is a member resource of / contacts/ {contactId} URI. The underscore JavaBean is a simple Contact class that uses id, name, and address as member fields. See listing 3 and listing 4 for details.

Listing 3. ContactsResource

@ Path ("/ contacts") public class ContactsResource {@ ContextUriInfo uriInfo;@ContextRequest request;@GET@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public List getContacts () {List contacts = > new ArrayList (); contacts.addAll (ContactStore.getStore (). Values ()); return contacts;} @ Path ("{contact}") public ContactResource getContact (@ PathParam ("contact") String contact) {return new ContactResource (uriInfo, request, contact);}}

There are several interesting places to pay attention to.

Context: use this annotation to inject context objects, such as Request, Response, UriInfo, ServletContext, and so on.

@ Path ("{contact}"): this is the @ Path annotation, combined with the root path "/ contacts" to form the URI of the child resource.

PathParam ("contact"): this comment injects the parameter into the path of the method parameter, which in this case is the contact id. Other available annotations are @ FormParam, @ QueryParam, and so on.

@ Produces: multiple MIME types are supported for responses. In this and previous examples, APPLICATION/XML will be the default MIME type.

You may also notice that the GET method returns a custom Java object instead of String (plain text), as shown in the previous Hello World example. The JAX-RS specification requires the ability to support multiple representation types, such as InputStream, byte [], JAXB elements, JAXB element collections, and so on, as well as the ability to serialize them into XML, JSON, or plain text as responses. I'll provide more information about presentation techniques, especially JAXB element representations, below.

Listing 4. ContactResource

Public class ContactResource {@ ContextUriInfo uriInfo;@ContextRequest request;String contact;public ContactResource (UriInfo uriInfo, Request request, String contact) {this.uriInfo = uriInfo;this.request = request;this.contact = contact;} @ GET@Produces ({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Contact getContact () {Contact cont= ContactStore.getStore () .get (contact); if (cont==null) throw new NotFoundException ("No such Contact."); return cont;}}

The code for ContactResource is simple and clear. Note the following:

Representation Type Contact:Contact is a simple JavaBean annotated by @ XmlRootElement, which allows it to be represented as XML or JSON.

ContactStore: this is an in-memory data repository based on HashMap, and its implementation is not important for this article.

Method

The HTTP method maps to the CRUD (create, read, update, and delete) operations of the resource. Although you can make some minor changes, such as making the PUT method create or update, the basic pattern is as follows:

HTTP GET: get / list / retrieve a single resource or collection of resources.

HTTP POST: create a new resource.

HTTP PUT: update an existing resource or collection of resources.

HTTP DELETE: deletes a resource or collection of resources.

Because I've already introduced the GET method, I'll start with POST. As with other methods, I still use the Contact example to illustrate.

POST

You usually create a new contact by filling out a form. That is, the HTML form POST to the server, which creates and maintains newly created contacts. Listing 5 demonstrates the server-side logic of this operation.

Listing 5. Accept form submission (POST) and create a new contact

@ POST@Produces (MediaType.TEXT_HTML) @ Consumes (MediaType.APPLICATION_FORM_URLENCODED) public void newContact (@ FormParam ("id") String id,@FormParam ("name") String name,@Context HttpServletResponse servletResponse) throws IOException {Contact c = newContact (id,name,new ArrayList ()); ContactStore.getStore () .put (id, c); URI uri = uriInfo.getAbsolutePathBuilder (). Path (id). Build (); Response.created (uri). Build (); servletResponse.sendRedirect (".. / pages/new_contact.html");}

Note the following parts of the example:

Consumes: declare that the method uses HTML FORM.

FormParam: inject the form input determined by the HTML property of the method.

@ Response.created (uri) .build (): build a new URI for the newly created contact (/ contacts/ {id}) and set the response code (201/created). You can use http://localhost:8080/Jersey/rest/contacts/ to access new contacts.

PUT

I use the PUT method to update existing resources. However, you can also update the implementation, or create a resource as shown in the code snippet in listing 6.

Listing 6. Accept PUT requests and create or update contacts

@ PUT@Consumes (MediaType.APPLICATION_XML) public Response putContact (JAXBElement jaxbContact) {Contact c = jaxbContact.getValue (); return putAndGetResponse (c);} private Response putAndGetResponse (Contact c) {Response res;if (ContactStore.getStore (). ContainsKey (c.getId () {res = Response.noContent (). Build ();} else {res = Response.created (uriInfo.getAbsolutePath ()). Build ();} ContactStore.getStore (). Put (c.getId (), c); return res;}

I also include many different concepts in this example, focusing on the following concepts:

The Consume XML:putContact () method accepts the APPLICATION/XML request type, and this input XML is bound to the Contact object using JAXB. You will find the client code in the next section.

The empty response has a different status code: the response to the PUT request has nothing, but has a different status code. If there is a contact in the data repository, I will update the contact and return to 204/no content. If I don't have a new contact, I'll create one and return 201/created.

DELETE

Implementing the DELETE method is very simple. For an example, see listing 7.

Listing 7. Delete contacts identified by their ID

@ DELETEpublic void deleteContact () {Contact c = ContactStore.getStore () .remove (contact); if (c==null) throw new NotFoundException ("No such Contact.");}

Representation form

In the previous section, I introduced several representation types. Now I'll take a quick look at it and delve deeper into the JAXB representation. Other supported representations are byte [], InputStream, File, and so on.

String: plain text.

Response: a generic HTTP response that contains customized content with different response codes.

Void: a null response with a 204/no content status code.

Resource Class: delegate the process to this resource class.

POJO: JavaBean annotated with @ XmlRootElement, which makes it a JAXB bean that can be bound to XML.

POJO collection: JAXB bean collection.

JAX-RS supports binding JavaBean to XML or JSON using JAXB (Java API for XML Binding) and vice versa. JavaBean must be annotated with @ XmlRootElement. Listing 8 uses Contact bean as an example. Fields that are not explicitly annotated with @ XmlElement will contain a XML element with the same name. Listing 9 shows the serialized XML and JSON representations for a Contact bean. The representation of the contact collection is the same, using it as a wrapper element by default.

Listing 8. Contact bean

@ XmlRootElementpublic class Contact {private String id;private String name;private List addresses;public Contact () {} public Contact (String id, String name, List addresses) {this.id = id;this.name = name;this.addresses = addresses;} @ XmlElement (name= "address") public List getAddresses () {return addresses;} public void setAddresses (List addresses) {this.addresses = addresses;} / / Omit other getters and setters}

Listing 9. A representation of Contact

XML representation: Shanghai Long Hua Street Shanghai Dong Quan Street huangyim Huang Yi MingJSON representation: {"contact": [{"address": [{"city": "Shanghai", "street": "Long Hua Street"}, {"city": "Shanghai", "street": "Dong Quan Street"}], "id": "huangyim", "name": "Huang Yi Ming"}]}

Clients that communicate with REST services

In the example so far, I have developed a RESTful Web service that supports CRUD. Now I'll explain how to use curl and the Jersey client API to communicate with the REST service. This way, I can test the server-side code and introduce more information about client-side technology.

Use curl to communicate with REST services

Curl is a popular command-line tool that sends requests to servers that use HTTP and HTTPS protocols. This is a good tool for communicating with RESTful Web services because it can send content through any HTTP method. Curl is already shipped with Linux and Mac, and has a utility that can be installed on the Windows platform.

Now, let's initialize the first curl command to get all the contacts. You can refer to listing 3 for the server-side code.

Curl http://localhost:8080/Jersey/rest/contacts

The response will use XML and contain all contacts.

Note that the getContacts () method also generates a response of type application/json MIME. You can also request this type of content.

Curl-HAccept:application/json http://localhost:8080/Jersey/rest/contacts

The response will be a JSON string containing all contacts.

Now, I will PUT a new contact. Notice that the putContact () method in listing 6 accepts XML and binds XML to the Contact object using JAXB.

Curl-X PUT-HContent-type:application/xml-data "foo bar" http://localhost:8080/Jersey/rest/contacts/foo

A new contact identified by "foo" will be added to the contact repository. You can use URI / contacts or / contacts/foo to verify contact sets or individual contacts.

Use Jersey Client to communicate with REST services

Jersey also provides a client library to help you communicate with the server and unit test RESTful services. The library is a generic implementation that can integrate any HTTP/HTTPS-based Web service.

The core class of the client is the WebResource class. You can use this class to build a request URL based on the root URI, then send the request and get the response. Listing 10 shows how to create a WebResource instance. Note that WebResource is a large object, so it is only created once.

Listing 10. Create a WebResource instance

Client c = Client.create (); WebResource r=c.resource ("http://localhost:8080/Jersey/rest/contacts");

The first Jersey client example sends an GET request to get all the contacts and prints the response status code and response content, as shown in listing 11.

Listing 11. GET all contacts and print responses

ClientResponse response = r.get (ClientResponse.class); System.out.println (response.getStatus ()); System.out.println (response.getHeaders (). Get ("Content-Type")); String entity = response.getEntity (String.class); System.out.println (entity)

Listing 12 shows another example of creating a new contact identified by "foo".

Listing 12. Create a contact

Address [] addrs = {new Address ("Shanghai", "Ke Yuan Street")}; Contact c = new Contact ("foo", "Foo Bar", Arrays.asList (addrs)); ClientResponse response = r.path (c.getId ()) .accept (MediaType.APPLICATION_XML) .put (ClientResponse.class, c); System.out.println (response.getStatus ())

Notice the API of the WebResource instance. It builds the URI, sets the request header, and invokes the request in one line of code. The content (Contact object) is automatically bound to the XML.

Listing 13 shows the last example of retrieving a contact identified by "foo" (created in the previous example) and then deleting that contact.

Listing 13. Retrieve the "foo" contact and delete

GenericType generic = new GenericType () {}; JAXBElement jaxbContact = r.path ("foo") .type (MediaType.APPLICATION_XML) .get (generic); Contact contact = jaxbContact.getValue (); System.out.println (contact.getId () + ":" + contact.getName ()); ClientResponse response = r.path ("foo") .delete (ClientResponse.class); System.out.println (response.getStatus ())

Note that when you want to get the JAXB bean response, you need to use the paradigm feature introduced in Java 2 Platform, Standard Edition (J2SE).

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report