Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot: Building Restful Web Services With Jersey

DZone's Guide to

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.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

In the previous posts, we have created a Spring Boot Quick Startcustomized 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.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
spring boot ,jersey ,web services ,java ,tutorial

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}