1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Quản trị mạng >

Chapter 23. Examples for Chapter 9

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.32 MB, 392 trang )


is application/xml, XML will be produced. If the Accept header is JSON, the Custom

er object will be outputted as JSON.

The second concept being highlighted here is that you can use the @Produces annotation

to dispatch to different Java methods. To illustrate this, we’ve added the getCustomer

String() method, which processes the same URL as getCustomer() but for a different

media type:

@GET

@Path("{id}")

@Produces("text/plain")

public Customer getCustomerString(@PathParam("id") int id)

{

return getCustomer(id).toString();

}



The Client Code

The client code for this example executes various HTTP GET requests to retrieve dif‐

ferent representations of a Customer. Each request sets the Accept header a little dif‐

ferently so that it can obtain a different representation. For example:

src/test/java/com/restfully/shop/test/CustomerResourceTest.java

public class CustomerResourceTest

{

@Test

public void testCustomerResource() throws Exception

{

... initialization code ...

System.out.println("*** GET XML Created Customer **");

String xml = client.target(location).request()

.accept(MediaType.APPLICATION_XML_TYPE)

.get(String.class);

System.out.println(xml);

System.out.println("*** GET JSON Created Customer **");

String json = client.target(location).request()

.accept(MediaType.APPLICATION_JSON_TYPE)

.get(String.class);

System.out.println(json);

}

}



The SyncInvoker.accept() method is used to initialize the Accept header. The client

extracts a String from the HTTP response so it can show you the request XML or JSON.



292



|



Chapter 23: Examples for Chapter 9



www.it-ebooks.info



Build and Run the Example Program

Perform the following steps:

1. Open a command prompt or shell terminal and change to the ex09_1 directory of

the workbook example code.

2. Make sure your PATH is set up to include both the JDK and Maven, as described

in Chapter 17.

3. Perform the build and run the example by typing maven install.



Example ex09_2: Conneg via URL Patterns

Chapter 9 discussed how some clients, particularly browsers, are unable to use the

Accept header to request different formats from the same URL. To solve this problem,

many JAX-RS implementations allow you to map a filename suffix (.html, .xml, .txt) to

a particular media type. RESTEasy has this capability. We’re going to illustrate this using

your browser as a client along with a slightly modified version of ex09_1.



The Server Code

A few minor things have changed on the server side. First, we add getCustomerHtml()

method to our CustomerResource class:

@GET

@Path("{id}")

@Produces("text/html")

public String getCustomerHtml(@PathParam("id") int id)

{

return "

Customer As HTML

"

+ getCustomer(id).toString() + "
";

}



Since you’re going to be interacting with this service through your browser, it might be

nice if the example outputs HTML in addition to text, XML, and JSON.

The only other change to the server side is in the configuration for RESTEasy:

src/main/webapp/WEB-INF/web.xml





resteasy.media.type.mappings



html : text/html,

txt : text/plain,

xml : application/xml



Example ex09_2: Conneg via URL Patterns



www.it-ebooks.info



|



293







...





The resteasy.media.type.mappings content parameter is added to define a mapping

between various file suffixes and the media types they map to. A comma separates each

entry. The suffix string makes up the first half of the entry and the colon character

delimits the suffix from the media type it maps to. Here, we’ve defined mappings be‐

tween .html and text/html, .txt and text/plain, and .xml and application/xml.



Build and Run the Example Program

Perform the following steps:

1. Open a command prompt or shell terminal and change to the ex09_2 directory of

the workbook example code.

2. Make sure your PATH is set up to include both the JDK and Maven, as described

in Chapter 17.

3. Perform the build and run the example by typing maven jetty:run.

The jetty:run target will run the servlet container so that you can make browser in‐

vocations on it. Now, open up your browser and visit http://localhost:8080/customers/1.

Doing so will show you which default media type your browser requests. Each browser

may be different. For me, Firefox 3.x prefers HTML, and Safari prefers XML.

Next, browse each of the following URLs: http://localhost:8080/customers/1.html, http://

localhost:8080/customers/1.txt, and http://localhost:8080/customers/1.xml. You should

see a different representation for each.



294



| Chapter 23: Examples for Chapter 9



www.it-ebooks.info



CHAPTER 24



Examples for Chapter 10



In Chapter 10, you learned about many of the concepts of HATEOAS and how to use

JAX-RS to add these principles to your RESTful web services. In this chapter, you’ll look

through two different examples. The first shows you how to introduce Atom links into

your XML documents. The second uses Link headers to publish state transitions within

a RESTful web service application.



Example ex10_1: Atom Links

This example is a slight modification of the ex06_1 example introduced in Chapter 21.

It expands the CustomerResource RESTful web service so that a client can fetch subsets

of the customer database. If a client does a GET /customers request in our RESTful

application, it will receive a subset list of customers in XML. Two Atom links are em‐

bedded in this document that allow you to view the next or previous sets of customer

data. Example output would be:





...





...




href="http://example.com/customers?start=5&size=2"

type="application/xml"/>


href="http://example.com/customers?start=1&size=2"

type="application/xml"/>





The next and previous links are URLs pointing to the same /customers URL, but they

contain URI query parameters indexing into the customer database.

295



www.it-ebooks.info



The Server Code

The first bit of code is a JAXB class that maps to the element. It must be

capable of holding an arbitrary number of Customer instances as well as the Atom links

for our next and previous link relationships. We can use the javax.ws.rs.core.Link

class with its JAXB adapter to represent these links:

src/main/java/com/restfully/shop/domain/Customers.java

import javax.ws.rs.core.Link;

...

@XmlRootElement(name = "customers")

public class Customers

{

protected Collection customers;

protected List links;

@XmlElementRef

public Collection getCustomers()

{

return customers;

}

public void setCustomers(Collection customers)

{

this.customers = customers;

}

@XmlElement(name="link")

@XmlJavaTypeAdapter(Link.JaxbAdapter.class)

public List getLinks()

{

return links;

}

public void setLinks(List links)

{

this.links = links;

}

@XmlTransient

public URI getNext()

{

if (links == null) return null;

for (Link link : links)

{

if ("next".equals(link.getRel())) return link.getUri();

}

return null;

}



296



| Chapter 24: Examples for Chapter 10



www.it-ebooks.info



Xem Thêm
Tải bản đầy đủ (.pdf) (392 trang)

×