Building RESTful Web Services with JAX-RS – Annotations

Post moved to

http://srinichekuri.com/2016/01/17/building-restful-web-services-with-jax-rs-annotations/

**********************************************************************

Let’s take a look at annotations that are used to build RESTful services. Based on the implementation framework that you are using, there might be many annotations. In this post we will discuss annotations that are supported by JAX-RS specs only.

@Path

  • @Path annotation identifies URI Path template
  • Can be used at class or method level.
  • Always specifies relative url to base url (host)
  • @Path value need not have leading or tailing slashes (/). JAX-RS treats them them the same either ways
  • Variables can be specified in @path as follows 
    • Multiple Variables can be specified. Eg @Path(“/users/{username_1}/{username_2}”)

 

//Variable in path is specified by {}
@Path("/users/{username}")
public class UserResource {

    @GET
    @Produces("text/xml")
    //variable specified in @Path can be accessed by @PathParam
    public String getUser(@PathParam("userName") String userName) {
        ...
    }
}


Request Method Designator Annotations (@GET, @POST, @PUT, @DELETE and @HEAD):

  • @GET – The Java method annotated with this will process HTTP GET requests.
  • @POST – The Java method annotated with this will process HTTP POST requests.
  • @PUT – The Java method annotated with this will process HTTP PUT requests.
  • @DELETE – The Java method annotated with this will process HTTP DELETE requests.
  • @HEAD – The Java method annotated with this will process HTTP HEAD requests.

Few logistics that should be followed to use JAX-RS for request methods designator annotations are as follows

  • Methods decorated with request method designators must return following:
    • void
    • A Java programming language type
    • A javax.ws.rs.core.Response Object.
  • Multiple parameters may be extracted from the URI using @PathParam or @QueryParam (Explained below).
  • The HTTP PUT and POST methods expect an HTTP request body.
  • Both @PUT and @POST can be used to create or update a resource.
  • POST can mean anything, so any semantics can be used. PUT has well defined semantics.When using PUT for creation, the client declares the URI for the newly created resource.
  • A common pattern is to use POST to create a resource and return a 201 response with a location header value is the URI to the newly created resource. In this pattern, the web service declares the URI for the newly created resource.

@Consumes and @Produces

@Produces annotation is used to specify the MIME media type that are sent back to client.

  • If specified on class level, all methods will follow it.
  • One can override class level by specifying this on method level.
  • If no methods in a resource are able to produce the MIME type in a client request, then JAX-RS runtime sends back an HTTP ‘406 Not Acceptable’ error.
  • Multiple MIME-types can be specified as follows
      • @Produces({“image/jpeg,image/png”})

     

 

@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html") //overides class level
    public String doGetAsHtml() {
        ...
    }
}


@Consumes represents the media types a resource  can accept.

  • If specified on class level, all methods will follow it.
  • One can override class level by specifying this on method level.
  • If a resource is unable to consume the MIME type of a client request, the JAX-RS runtime sends back an HTTP “415 (‘Unsupported Media Type’)” error.
  • If @consumes is used on method that returns ‘void’ then HTTP 204 (‘No Content’) error is returned.

    @POST@Consumes(“text/plain”)public void postClichedMessage(String message) {    // Store the message }

@Path("/myResource")
@Consumes("multipart/related")
public class SomeResource {
    @POST
    public String doPost(MimeMultipart mimeMultipartData) {
        ...
    }

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public String doPost2(FormURLEncodedProperties formData) {
        ...
    }
}

 

Request Parameters (@QueryParam, @PathParam, @DefaultValue, @MatrixParam, @HeaderParam, @CookieParam, @FormParam)

Both @QueryParam and @PathParam can be used only on following Java types:

  • All primitive types except char.
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single String argument.
  • Any class with static method named valueOf (String) that accepst a single String argument
  • List<T>, Set<T> or SortedSet<T>, where T matches the already listed criteria.

 

@Path(&quot;smooth&quot;)
@GET
public Response smooth(
        @DefaultValue(&quot;4&quot;) @QueryParam(&quot;number&quot;) int colorNumber,
        @DefaultValue(&quot;red&quot;) @QueryParam(&quot;last-color&quot;) String color
        ) { ... }

Advertisements

Building RESTful Web Services with JAX-RS – Introduction

Post moved to

http://srinichekuri.com/2016/01/17/building-restful-web-services-with-jax-rs-introduction/

**********************************************************************

Introduction to REST:

REST Stands for REpresentational State Transfer. REST  is built to work best in web and uses a stateless communication protocol, typically HTTP. Following principles make RESTful application simple, lightweight and fast.

  • URIs are used to identify resources (services).
  • Uniform Indentification for CRID activities
    • Create – PUT
    • Read – GET
    • Update – POST
    • Delete – DELETE
  • Resources (Services) are decoupled from representation so their content can be accessed in variety of formats. Eg: HTML, Plain Text, XML, JSON etc
  • As Rest Services are Stateless, Stateful interaction can be done by URI rewriting, cookies and hidden fields.

Advantages of REST

  • Better Performance
  • Scalability
  • Modifiability.

Disadvantages of REST

  • Less Secure

<Put in an HelloWorldRest Service here with  text on what annotation means what>

Step by Step guide- Hello World REST Service

Post moved to

http://srinichekuri.com/2016/01/17/step-by-step-guide-hello-world-rest-service/

**********************************************************************

This post is a step by step guide for a Hello world REST Service using JAX-RS. I am using Eclipse (Mars Edition) and Apache Tomcat for this tutorial. Also I am using Maven for build automation. If you are beginner or  if you have not yet configured your workspace then I recommend these links before reading any further.

Apache Wink is used for JAX-RS implementation for this tutorial.

Step 1: Create a new Dynamic Web Application

Create a new dynamic web application (named HelloWorldRest for this tutorial). Also convert the project into ‘Maven Project’ (This is an optional step if you are planning to use Maven).

Step 2: Update dependencies for Apache Wink

Add these dependencies to pom.xml

<dependency>
 <groupId>org.apache.wink</groupId>
 <artifactId>wink-server</artifactId>
 <version>1.4</version>
 </dependency>
 <dependency>
 <groupId>org.apache.wink</groupId>
 <artifactId>wink-common</artifactId>
 <version>1.4</version>
</dependency>

If you are not using Maven then download the following jar version into WEB-INF/lib folder.

activation.jar -> 1.1 Version
commons-lang.jar -> 2.3 Version
geronimo annotation_1.1_spec.jar -> 1.0 Version
geronimo-jaxrs_1.1_spec.jar -> 1.0 Version
jaxb-api.jar -> 2.2 Version
jaxb-impl.jar -> 2.2.1.1 Version
slf4j-api.jar -> 1.6.1 Version
stax-api.jar -> 1.0-2 Version
wink-common.jar -> 1.4 Version
wink-server.jar -> 1.4 Version

Step -3: Add code for REST Service

Add below code for HelloWorldResource

 

package com.test.helloworld.resource;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path(&quot;/helloworld&quot;)
public class HelloWorldResource {

	@GET
	 public String getMessage() {
		System.out.println(&quot;Returning Message&quot;);
		return &quot;Hello World!&quot;;
	 }
}


Add below code for HelloWorldApplication

 

package com.test.helloworld;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import com.test.helloworld.resource.HelloWorldResource;

public class HelloWorldApplication extends Application{

	@Override
	 public Set&lt;Class&lt;?&gt;&gt; getClasses() {
		 Set&lt;Class&lt;?&gt;&gt; classes = new HashSet&lt;Class&lt;?&gt;&gt;();
		 classes.add(HelloWorldResource.class);
		 return classes;
	}
}


Add below entries to web.xml

<servlet>
 <servlet-name>HelloWorldApp</servlet-name>
 <servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
 <init-param>
  <param-name>javax.ws.rs.Application</param-name>
  <param-value>com.test.helloworld.HelloWorldApplication</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>HelloWorldApp</servlet-name>
  <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Step-4: Test HelloWorld REST Service

helloworld_rest_service