JAX-RS Path Annotation Example

0

Any Java class that you want to be recognized as JAX-RS services must have @Path annotation.

@javax.ws.rs.Path annotation is a type annotation so it can be placed either at class level or method level.

Another annotation that is required is a resource method designator annotation to identify the HTTP request method to be handled by a resource method, for example, @GET, @PUT, @POST or @DELETE.

A JAX-RS web resource must have at least one method must be annotated with @Path or a resource method designator annotation.

Dependencies

We will use Jersey as the JAX-RS provider. The example described here uses the lightweight Grizzly HTTP server.

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 -DarchetypeGroupId=org.glassfish.jersey.archetypes 
-DinteractiveMode=false -DgroupId=com.javarticles.rest -DartifactId=JaxRsPathExample -DarchetypeVersion=2.22.1

The generated pom.xml would look like below:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.javarticles.rest</groupId>
    <artifactId>JaxRsPathExample</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JaxRsPathExample</name>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.javarticles.rest.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jersey.version>2.22.1</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Create Maven RESTFul Project in Eclipse

Click on File->New->Other->Maven->Maven Project. The project creation wizard will open up. In the filter box enter ‘jersey’.
From the list of Group Id/Archtype Id, select Jersey provided archetype ‘jersey-quickstart-grizzly2’ with groupId ‘org.glassfish.jersey.archetypes’.

Select jersey-quickstart-grizzly2

Select jersey-quickstart-grizzly2

Click on next, enter project’s group Id and artifactId and finish the project creation.

JAX-RS Simple Resource Example

A resource class annotated with @Path is called the root resource. Root resource classes provide the roots of the resource class tree and provide access to sub-resources. The value of the @Path annotation is a relative URI path template whose base URI is provided by the combination of the deployment context and the application path.

For a Java class to be eligible to receive any HTTP requests, the class must be annotated with at least the @Path(“/”) expression.

In the below example, SimpleResource is the root class as it is annotated with @Path and method simpleRequest() will handle the incoming ‘Get’ requests as it is annotated with @GET. The path value specified is just “/”.

SimpleResource:

package com.javarticles.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("/")
public class SimpleResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String simpleRequest() {
        return "This is simple request with no relative path";
    }
}

When you create the project based on jersey-quickstart-gizzly2 artifact, a main class is automatically created which will help us host the web resources. If you note, it contains the package name where the web resources are residing. You may want to change this based on the list of packages holding the web resource classes. In our example, all the resources are residing in package com.javarticles.rest

final ResourceConfig rc = new ResourceConfig().packages("com.javarticles.rest");

Main:

package com.javarticles.rest.JaxRsPathExample;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8280/myapp/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.javarticles.rest.JaxRsPathExample package
        final ResourceConfig rc = new ResourceConfig().packages("com.javarticles.rest");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        System.in.read();
        server.stop();
    }
}

When you enter http://localhost:8280/myapp/ in the browser, SimpleResource.simpleRequest() will be called to handle the request.

Output:

This is simple request with no relative path

JAX-RS Resource with @Path Value

In ResourceOne class below, we specify a @Path value other than “/”. For example, @Path("resourceone"). If the absolute base URI of our server is http://localhost:8280/myapp/, then method ResourceOne.request1() will handle request http://localhost:8280/myapp/resourceone.
Value specified in @Path annotation, resourceone, represents the relative root URI of http://localhost:8280/myapp/.

ResourceOne:

package com.javarticles.rest.JaxRsPathExample;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("resourceone")
@Produces(MediaType.TEXT_PLAIN)
public class ResourceOne {

    @GET
    public String request1() {
        return "This is request1";
    }    
}

Enter http://localhost:8280/myapp/resourceone/

Output:

This is request1

You can have one more source for the same @Path value.
For example, OneMoreResourceOne contains a sub-resource at @Path("request2").

OneMoreResourceOne:

package com.javarticles.rest.JaxRsPathExample;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("resourceone")
public class OneMoreResourceOne {
    
    @Path("request2")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String request2() {
        return "This is request2";
    }    
}

Enter http://localhost:8280/myapp/resourceone/request2

Output:

This is request2

@PathParam Example

@Path can have complex matching expressions so that you can be more specific about what requests get bound to which incoming URIs. The URI template parameter can be specified using an open brace “{” and close brace “}”, for example @Path("{userid}"). The value of template parameter can be extracted using annotation @PathParam. The URI path parameter can be injected via @PathParam on a field, property or method parameter.

ResourceTwo:

package com.javarticles.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("resourcetwo")
public class ResourceTwo {

    @Path("{userid}")
    @GET
    public Response getUser(@PathParam("userid") String userid) {
        return Response.status(200).entity("User is " + userid).build();
    }
}

Enter http://localhost:8280/myapp/resourcetwo/Joe.

Output:

User is Joe

Download the source code

This was an example about JAX-RS @Path annotation.

You can download the source code here: JaxRsPathExample.zip
Share.

Comments are closed.