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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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.

Gaurav Rai Mazra user avatar by
Gaurav Rai Mazra
·
Mar. 06, 17 · Tutorial
Like (12)
Save
Tweet
Share
58.66K 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.

Popular on DZone

  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]
  • A Real-Time Supply Chain Control Tower Powered by Kafka
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • How to Develop a Portrait Retouching Function

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: