DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Node.js Http Module to Consume Spring RESTful Web Application

Trending

  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • A Modern Stack for Building Scalable Systems
  • Ensuring Configuration Consistency Across Global Data Centers
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Building Restful Web Services With Jersey

Spring Boot: Building Restful Web Services With Jersey

If you want to build Restful web services, you can use Spring Boot, Jersey, and Undertow to set up a system for web requests.

By 
Gaurav Rai Mazra user avatar
Gaurav Rai Mazra
·
Mar. 06, 17 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
59.7K Views

Join the DZone community and get the full member experience.

Join For Free

In the previous posts, we have created a Spring Boot Quick Start, customized our embedded server and properties, and run specific code after a Spring Boot application starts.

Now, in this post, we will create Restful web services with Jersey, and deployed on Undertow, as a Spring Boot Application.

Adding Dependencies in Your POM.xml

We will add spring-boot-starter-parent as a parent of our maven-based project. The added benefit of this is version management for Spring dependencies.

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.0.RELEASE</version>
</parent>


Adding the Spring-Boot-Starter-Jersey Dependency

This will add/configure the Jersey-related dependencies.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>


Adding the Spring-Boot-Starter-Undertow Dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>


These are all the necessary spring-boot-starters we require to build Restful web services with Jersey.

Creating a Root Resource/Controller Class

What Are Root Resource Classes?

Root resource classes are POJOs that are either annotated with @Path, or have at least one method annotated with @Path, or a request method designator, such as @GET, @PUT, @POST, or @DELETE.

@Component
@Path("/books")
public class BookController {
    private BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GET
    @Produces("application/json")
    public Collection getAllBooks() {
        return bookService.getAllBooks();
    }

    @GET
    @Produces("application/json")
    @Path("/{oid}")
    public Book getBook(@PathParam("oid") String oid) {
        return bookService.getBook(oid);
    }

    @POST
    @Produces("application/json")
    @Consumes("application/json")
    public Response addBook(Book book) {
        bookService.addBook(book);
        return Response.created(URI.create("/" + book.getOid())).build();
    }

    @PUT
    @Consumes("application/json")
    @Path("/{oid}")
    public Response updateBook(@PathParam("oid") String oid, Book book) {
        bookService.updateBook(oid, book);
        return Response.noContent().build();
    }

    @DELETE
    @Path("/{oid}")
    public Response deleteBook(@PathParam("oid") String oid) {
        bookService.deleteBook(oid);
        return Response.ok().build();
    }
}


We have created a BookController class and used JAX-RS annotations.

  • @Path is used to identify the URI path (relative) that a resource class or class method will serve requests for.

  • @PathParam is used to bind the value of a URI template parameter or a path segment containing the template parameter to a resource method parameter, resource class field, or resource class bean property. The value is URL decoded unless this is disabled using the @Encoded annotation.

  • @GET indicates that annotated method handles HTTP GET requests.

  • @POST indicates that annotated method handles HTTP POST requests.

  • @PUT indicates that annotated method handles HTTP PUT requests.

  • @DELETE indicates that annotated method handles HTTP DELETE requests.

  • @Produces defines a media-type that the resource method can produce.

  • @Consumes defines a media-type that the resource method can accept.

You might have noticed that we have annotated BookController with @Component, which is Spring's annotation, and registered it as a bean. We have done so to benefit Spring's DI for injecting the BookService service class.

Creating a JerseyConfiguration Class

We created a JerseyConfiguration class that extends the ResourceConfig from package org.glassfish.jersey.server, which configures the web application. In the setUp(), we registered BookController and GenericExceptionMapper.

@ApplicationPath identifies the application path that serves as the base URI for all the resources.

Registering Exception Mappers

There could be a case where some exceptions occur in the resource methods (runtime/checked). You can write your own custom exception mappers to map Java exceptions to javax.ws.rs.core.Response.

@Provider
public class GenericExceptionMapper implements ExceptionMapper {

    @Override
    public Response toResponse(Throwable exception) {
        return Response.serverError().entity(exception.getMessage()).build();
    }
}


We have created a generic exception handler by catching Throwable. Ideally, you should write a finer-grained exception mapper.

What Is @Provider Annotation?

It marks an implementation of an extension interface that should be discoverable by JAX-RS runtime during a provider scanning phase.

We have also created service BookService and model Book. You can grab the full code from GitHub.

Running the Application

You can use maven to directly run it with mvn spring-boot:run, or you can create a JAR and run it.

Testing the REST Endpoints

I have used the PostMan extension available in Chrome to test REST services. You can use any package/API/software to test it.

This is how we create Restful web services with Jersey in conjunction with Spring Boot. I hope you find this post informative and helpful when creating your first, but hopefully not your last, Restful web service.

Spring Framework Spring Boot Web Service REST Web Protocols application Media type Requests Dependency POST (HTTP)

Published at DZone with permission of Gaurav Rai Mazra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Node.js Http Module to Consume Spring RESTful Web Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!