JAX-RS Web Services
- JAX-RS Web Services Concepts
- List of Annotation used in JAX-RS
- JAX-RS Web Services Example using Jersey
JAX-RS Web Services Concepts |
RESTful Web Services
In Java EE 6, JAX-RS provides the functionality for Representational State Transfer (RESTful) web services. REST is well suited for basic, ad hoc integration scenarios. RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service-API definitions.
Project Jersey is the production-ready reference implementation for the JAX-RS specification. Jersey implements support for the annotations defined in the JAX-RS specification, making it easy for developers to build RESTful web services with Java and the Java Virtual Machine (JVM).
Because RESTful web services use existing well-known W3C and Internet Engineering Task Force (IETF) standards (HTTP, XML, URI, MIME) and have a lightweight infrastructure that allows services to be built with minimal tooling, developing RESTful web services is inexpensive and thus has a very low barrier for adoption. You can use a development tool such as NetBeans IDE to further reduce the complexity of developing RESTful web services.
A RESTful design may be appropriate when the following conditions are met.
- The web services are completely stateless. A good test is to consider whether the interaction can survive a restart of the server.
- A caching infrastructure can be leveraged for performance. If the data that the web service returns is not dynamically generated and can be cached, the caching infrastructure that web servers and other intermediaries inherently provide can be leveraged to improve performance. However, the developer must take care because such caches are limited to the HTTP GET method for most servers.
- The service producer and service consumer have a mutual understanding of the context and content being passed along. Because there is no formal way to describe the web services interface, both parties must agree out of band on the schemas that describe the data being exchanged and on ways to process it meaningfully. In the real world, most commercial applications that expose services as RESTful implementations also distribute so-called value-added toolkits that describe the interfaces to developers in popular programming languages.
- Bandwidth is particularly important and needs to be limited. REST is particularly useful for limited-profile devices, such as PDAs and mobile phones, for which the overhead of headers and additional layers of SOAP elements on the XML payload must be restricted.
- Web service delivery or aggregation into existing web sites can be enabled easily with a RESTful style. Developers can use such technologies as JAX-RS and Asynchronous JavaScript with XML (AJAX) and such toolkits as Direct Web Remoting (DWR) to consume the services in their web applications. Rather than starting from scratch, services can be exposed with XML and consumed by HTML pages without significantly refactoring the existing web site architecture. Existing developers will be more productive because they are adding to something they are already familiar with rather than having to start from scratch with new technology.
- RESTful web services can be build using both NetBeans IDE and the Maven project management tool.
JAX-RS : makes it easier to write web applications that apply some or all of the constraints of the REST style to induce desirable properties in the application, such as loose coupling (evolving the server is easier without breaking existing clients), scalability (start small and grow), and architectural simplicity (use off-the-shelf components, such as proxies or HTTP routers). You would choose to use JAX-RS for your web application because it is easier for many types of clients to consume RESTful web services while enabling the server side to evolve and scale. Clients can choose to consume some or all aspects of the service and mash it up with other web-based services.
List of Annotation used in JAX-RS |
Lists of Java programming annotations that are defined by JAX-RS, with a brief description of how each is used.
Annotation | Description |
---|---|
@Path |
The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted: for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user and pass it to the application as a variable in the URI: /helloworld/{username}. |
@PathParam |
The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. |
@QueryParam |
The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters. |
@Consumes |
The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. |
@Produces |
The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client: for example, “text/plain”. |
@Provider |
The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity and that can be built using Response.ResponseBuilder. |
@GET |
The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
@POST |
The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
@PUT |
The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
@DELETE |
The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
@HEAD |
The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. |
JAX-RS Web Services Example |
Create JAX-RS RESTful Web services using Jersey
Step1: Create web application with following java file and web.xml as below
TemperatureConversionService.java
package com.javaskool;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("TempConversionService")
public class TemperatureConversionService {
@GET
@Path("/FtoC/{f}")
@Produces(MediaType.TEXT_XML)
public String FahrenheitToCelsius(@PathParam("f") double fahrenheit) {
double cel= ((((fahrenheit) - 32) / 9) * 5);
return "<FahrenheitToCelsius>"
+ "<Fahrenheit>" + fahrenheit + "</Fahrenheit>"
+ "<Celsius>" + cel + "</Celsius>"
+ "</FahrenheitToCelsius>";
}
@Path("/CtoF/{c}")
@GET
@Produces(MediaType.TEXT_XML)
public String CelsiusToFahrenheit(@PathParam("c") double cel) {
double fahrenheit= ((((cel) * 9) / 5) + 32);
return "<CelsiusToFahrenheit>"
+ "<Celsius>" + cel + "</Celsius>"
+ "<Fahrenheit>" + fahrenheit + "</Fahrenheit>"
+ "</CelsiusToFahrenheit>";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" class="nWebApp_ID" version="2.5">
<display-name>JAX-RSWebservicesJersey</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.javaskool</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>TempConversionService</title>
</head>
<body>
<a href="rest/TempConversionService/FtoC/102.5">FahrenheitToCelsius</a>
<br><br>
<a href="rest/TempConversionService/CtoF/40.5">CelsiusToFahrenheit</a>
</body>
</html>
Step2: Run web application on apache tomcat 6.0 above
Step 3: You can also make java application as below and use web services
TempConversionServiceClient.java
package com.javaskool.client;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class TempConversionServiceClient {
static final String REST_URI = "http://localhost:8080/JAX-RSWebservicesJersey";
static final String FahrenheitToCelsius = "/TempConversionService/FtoC/";
static final String CelsiusToFahrenheit = "/TempConversionService/CtoF/";
public static void main(String[] args) {
int fahrenheit=104;
int celsius=40;
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(REST_URI);
WebResource addService = service.path("rest").path(FahrenheitToCelsius+fahrenheit);
System.out.println("FahrenheitToCelsius Response: " + getResponse(addService));
System.out.println("FahrenheitToCelsius Output as XML: " + getOutputAsXML(addService));
System.out.println("---------------------------------------------------");
WebResource subService = service.path("rest").path(CelsiusToFahrenheit+celsius);
System.out.println("CelsiusToFahrenheit Response: " + getResponse(subService));
System.out.println("CelsiusToFahrenheit Output as XML: " + getOutputAsXML(subService));
System.out.println("---------------------------------------------------");
}
private static String getResponse(WebResource service) {
return service.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();
}
private static String getOutputAsXML(WebResource service) {
return service.accept(MediaType.TEXT_XML).get(String.class);
}
}
Output
FahrenheitToCelsius Response: GET http://localhost:8080/JAX-RSWebservicesJersey/rest/TempConversionService/FtoC/104 returned a response status of 200 OK
FahrenheitToCelsius Output as XML: <FahrenheitToCelsius><Fahrenheit>104.0</Fahrenheit><Celsius>40.0</Celsius></FahrenheitToCelsius>
---------------------------------------------------
CelsiusToFahrenheit Response: GET http://localhost:8080/JAX-RSWebservicesJersey/rest/TempConversionService/CtoF/40 returned a response status of 200 OK
CelsiusToFahrenheit Output as XML: <CelsiusToFahrenheit><Celsius>40.0</Celsius><Fahrenheit>104.0</Fahrenheit></CelsiusToFahrenheit>
---------------------------------------------------
Recent Comments