Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – Spring Top – Temp – Non-Geo (Lightrun)

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

Jersey is an open source framework for developing RESTful Web Services. It serves as a reference implementation of JAX-RS.

In this article, we'll explore the creation of a RESTful Web Service using Jersey 2. Also, we'll use Spring's Dependency Injection (DI) with Java configuration.

2. Maven Dependencies

Let's begin by adding dependencies to the pom.xml:


Also, for Spring integration we have to add the jersey-spring4 dependency:


The latest version of these dependencies is available at jersey-container-servlet, jersey-media-json-jackson and jersey-spring4.

3. Web Configuration

Next, we need to set up a web project to do Servlet configuration. For this, we'll use Spring's WebApplicationInitializer:

public class ApplicationInitializer 
  implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) 
      throws ServletException {
        AnnotationConfigWebApplicationContext context 
          = new AnnotationConfigWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(context));
          "contextConfigLocation", "com.baeldung.server");

Here, we're adding the @Order(Ordered.HIGHEST_PRECEDENCE) annotation to ensure that our initializer is executed before the Jersey-Spring default initializer.

4. A Service Using Jersey JAX-RS

4.1. Resource Representation Class

Let's use a sample resource representation class:

public class Employee {
    private int id;
    private String firstName;

    // standard getters and setters

Note that JAXB annotations like @XmlRootElement are required only if XML support is needed (in addition to JSON).

4.2. Service Implementation

Let's now look at how we can use JAX-RS annotations to create RESTful web services:

public class EmployeeResource {
    private EmployeeRepository employeeRepository;

    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Employee getEmployee(@PathParam("id") int id) {
        return employeeRepository.getEmployee(id);

    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response addEmployee(
      Employee employee, @Context UriInfo uriInfo) {
        employeeRepository.addEmployee(new Employee(employee.getId(), 
          employee.getFirstName(), employee.getLastName(), 
        return Response.status(Response.Status.CREATED.getStatusCode())

The @Path annotation provides the relative URI path to the service. We can also embed variables within the URI syntax, as the {id} variable shows. Then, the variables will be substituted at runtime. To obtain, the value of the variable we can use the @PathParam annotation.

@GET, @PUT, @POST, @DELETE and @HEAD define the HTTP method of the request, which will be processed by annotated methods.

The @Produces annotation defines the endpoint's response type (MIME media type). In our example, we've configured it to return either JSON or XML depending on the value of HTTP header Accept (application/json or application/xml).

On the other hand, the @Consumes annotation defines the MIME media types that the service can consume. In our example, the service can consume either JSON or XML depending on the HTTP header Content-Type (application/json or application/xml).

The @Context annotation is used to inject information into a class field, bean property or method parameter. In our example, we're using it to inject UriInfo. We can also use it to inject ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse.

5. Using ExceptionMapper

ExceptionMapper allows us to intercept the exceptions and return appropriate HTTP response code to the client. In the following example, HTTP response code 404 is returned if EmployeeNotFound exception is thrown:

public class NotFoundExceptionHandler 
  implements ExceptionMapper<EmployeeNotFound> {
    public Response toResponse(EmployeeNotFound ex) {
        return Response.status(Response.Status.NOT_FOUND).build();

6. Managing Resource Classes

Finally, let's wire up all service implementation classes and exception mappers against an application path:

public class RestConfig extends Application {
    public Set<Class<?>> getClasses() {
        return new HashSet<Class<?>>(

7. API Testing

Let's now test the APIs with some live tests:

public class JerseyApiLiveTest {

    private static final String SERVICE_URL
      = "http://localhost:8082/spring-jersey/resources/employees";

    public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() 
      throws ClientProtocolException, IOException {
        HttpUriRequest request = new HttpGet(SERVICE_URL);

        HttpResponse httpResponse = HttpClientBuilder

          .getStatusCode(), HttpStatus.SC_OK);

8. Conclusion

In this article, we've introduced the Jersey framework and developed a simple API. We've used Spring for Dependency Injection features. We have also seen the use of ExceptionMapper.

As always, the full source code is available in this Github project.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

REST bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course :

REST footer banner
Comments are closed on this article!