Skip to main content

Jersey JAX-RS Framework - Step by Step Guide for Developing RESTful web services


Overview

Jersey is a Java framework for developing RESTful web services. It is an implementation of JAX-RS reference.  In addition to JAX-RS , Jersey has its extended APIs that eases the development of restful web services and client development. In this tutorial, I will guide you through the steps to jump-start developing the RESTful web services using the Jersey framework.


Requirements for this tutorial

  • Eclipse
  • Maven
  • Jersey Framework
  • Tomcat or any other Servlet container

STEP 1

Open the Eclipse and create an empty Maven web project. Add the following dependencies
  <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>${jaxrs.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
          <groupId>org.glassfish.jersey.inject</groupId>
          <artifactId>jersey-hk2</artifactId>
          <version>${jersey2.version}</version>
        </dependency>  
   </dependencies>


STEP 2

Create a class with the following code

package com.techieshah;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import com.techieshah.domainmodel.BlogPost;

/*Author: https://techieshah.blogspot.com*/

@Path("/")
public class JerseyExample {
  
    @GET
    public BlogPost get(@QueryParam("id") Integer id){
       
        for(BlogPost blogPost : BlogPostRepository.blogPosts) {
            if(blogPost.id == id) {
                return blogPost;
            }
        }
        return null;
    }
    
    @POST
    public String post( BlogPost blogPost){
        BlogPostRepository.blogPosts.add(blogPost);
        return "Blog Post saved successfully";
    }
    
    @PUT
    public String put(BlogPost updatedBlogPost) {
        for(BlogPost blogPost : BlogPostRepository.blogPosts) {
            if(blogPost.id == updatedBlogPost.id) {
               blogPost.name = updatedBlogPost.name;
               blogPost.tag = updatedBlogPost.tag;
               blogPost.content = updatedBlogPost.content;
            }
        }
        return "Blog Post updated successfully";
    }
    
    @DELETE
    public String delete(@QueryParam("id") Integer id){
        
        for(BlogPost blogPost : BlogPostRepository.blogPosts) {
            if(blogPost.id == id) {
                BlogPostRepository.blogPosts.remove( blogPost );
                break;
            }
        }
        return "Blog Post deleted successfully";
    }

}

@Path("/")
This specifies the URL path for this resource.

@QueryParam
This is used to specify the Query parameters in the URL

The following annotations are used to map the class functions against the corresponding HTTP methods
@GET (for selection), @POST (for insert) , @PUT (for update) and @DELETE (for delete)


STEP 3

Modify the web.xml 

<servlet>
<servlet-name>JerseyService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.techieshah</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyService </servlet-name>
<url-pattern>/api/*</url-pattern>

</servlet-mapping>

Now our web services are ready for testing. We can use any Rest client to test it.


Request 

GET  http://localhost:9080/jerseywsexample/api?id=1

Response

<blogPost> <id>1</id> <name>spring framework</name> <tag>ws</tag> <content>first example of rest web services</content> </blogPost>

Similarly, we can test the remaining methods i.e. POST, PUT and DELETE.

Complete source code can be downloaded from Jersey JAX-RS Example .




Comments

Popular posts from this blog

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/

spark-submit java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp

Exception  Exception in thread "main" java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp         at SparkPi$.main(SparkPi.scala:14)         at SparkPi.main(SparkPi.scala)         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) Problem: It seems that you have compiled and generated your jar file with an upper version of the Scala compiler than the one spark is using. Solution Step 1 Run the following command from spark-installed-directory\bin spark-shell.cmd (or.sh) and note the Scala version, My Spark version was 2.4.3 and Scala version 2.11.12 Step 2 Change the scala version into your build.sbt to 2.11.12 (per your configuration). My build.sbt is name := "SparkPi Project" version := "1.0" scalaVersion := "...