eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

Jersey is an open-source framework for developing RESTFul Web Services.

As well as serving as the JAX-RS reference implementation it also includes a number of extensions to further simplify web application development.

In this tutorial, we’ll create a small example application that uses the Model-View-Controller (MVC) extension offered by Jersey.

To learn how to create an API with Jersey, check out this write-up here.

2. MVC in Jersey

Jersey contains an extension to support the Model-View-Controller (MVC) design pattern.

First of all, in the context of Jersey components, the Controller from the MVC pattern corresponds to a resource class or method.

Likewise, the View corresponds to a template bound to a resource class or method. Finally, the model represents a Java object returned from a resource method (Controller).

To use the capabilities of Jersey MVC in our application, we first need to register the MVC module extension that we wish to use.

In our example, we’re going to use the popular Java template engine Freemarker. This is one of the rendering engines supported by Jersey out of the box along with Mustache and standard Java Server Pages (JSP).

For more information about how MVC works, please refer to this tutorial.

3. Application Setup

In this section, we’ll start by configuring the necessary Maven dependencies in our pom.xml.

Then, we’ll take a look at how to configure and run our server using a simple embedded Grizzly server.

3.1. Maven Dependencies

Let’s start by adding the Jersey MVC Freemarker extension.

We can get the latest version from Maven Central:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-mvc-freemarker</artifactId>
    <version>3.1.1</version>
</dependency>

We’re also going to need the Grizzly servlet container.

Again we can find the latest version in Maven Central:

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>3.1.1</version>
</dependency>

3.2. Configuring the Server

To make use of the Jersey MVC templating support in our application we need to register the specific JAX-RS features provided by the MVC modules.

With this in mind, we define a custom resource configuration:

public class ViewApplicationConfig extends ResourceConfig {    
    public ViewApplicationConfig() {
        packages("com.baeldung.jersey.server");
        property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, "templates/freemarker");
        register(FreemarkerMvcFeature.class);;
    }
}

In the above example we configure three items:

  • First, we use the packages method to tell Jersey to scan the com.baeldung.jersey.server package for classes annotated with @Path. This will register our FruitResource
  • Next, we configure the base path in order to resolve our templates. This tells Jersey to look in the /src/main/resources/templates/freemarker for Freemarker templates
  • Finally, we register the feature that handles the Freemarker rendering via the FreemarkerMvcFeature class

3.3. Running the Application

Now let’s look at how to run our web application. We’ll use the exec-maven-plugin to configure our pom.xml to execute our embedded web server:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <configuration>                
        <mainClass>com.baeldung.jersey.server.http.EmbeddedHttpServer</mainClass>
    </configuration>
</plugin>

Let’s now compile and run our application using Maven:

mvn clean compile exec:java
...
Jul 28, 2018 6:21:08 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Application started.
Try out http://localhost:8082/fruit
Stop the application using CTRL+C

Go to the browser URL – http://localhost:8080/fruit. Voila, the “Welcome Fruit Index Page!” is displayed.

4. MVC Templates

In Jersey, the MVC API consists of two classes to bind the model to the view namely Viewable and @Template

In this section we’ll explain three different ways of linking templates to our view:

  • Using the Viewable class
  • Using the @Template annotation
  • How to handle errors with MVC and pass them to a specific template

4.1. Using Viewable in a Resource Class

Let’s start by looking at Viewable:

@Path("/fruit")
public class FruitResource {
    @GET
    public Viewable get() {
        return new Viewable("/index.ftl", "Fruit Index Page");
    }
}

In this example, the FruitResource JAX-RS resource class is the controller. The Viewable instance encapsulates the referenced data model which is a simple String.

Furthermore, we also include a named reference to the associated view template – index.ftl.

4.2. Using @Template on a Resource Method

There’s no need to use Viewable every time we want to bind a model to a template.

In this next example, we’ll simply annotate our resource method with @Template:

@GET
@Template(name = "/all.ftl")
@Path("/all")
@Produces(MediaType.TEXT_HTML)
public Map<String, Object> getAllFruit() {
    List<Fruit> fruits = new ArrayList<>();
    fruits.add(new Fruit("banana", "yellow"));
    fruits.add(new Fruit("apple", "red"));
    fruits.add(new Fruit("kiwi", "green"));

    Map<String, Object> model = new HashMap<>();
    model.put("items", fruits);
    return model;
}

In this example, we’ve used the @Template annotation. This avoids wrapping our model directly in a template reference via Viewable and makes our resource method more readable.

The model is now represented by the return value of our annotated resource method – a Map<String, Object>. This is passed directly to the template all.ftl which simply displays our list of fruit.

4.3. Handling Errors with MVC

Now let’s take a look at how to handle errors using the @ErrorTemplate annotation:

@GET
@ErrorTemplate(name = "/error.ftl")
@Template(name = "/named.ftl")
@Path("{name}")
@Produces(MediaType.TEXT_HTML)
public String getFruitByName(@PathParam("name") String name) {
    if (!"banana".equalsIgnoreCase(name)) {
        throw new IllegalArgumentException("Fruit not found: " + name);
    }
    return name;
}

Generally speaking, the purpose of the @ErrorTemplate annotation is to bind the model to an error view. This error handler will take care of rendering the response when an exception is thrown during the processing of a request.

In our simple Fruit API example if no errors occur during processing then the named.ftl template is used to render the page. Otherwise, if an exception is raised then the error.ftl template is shown to the user.

In this case, the model is the thrown exception itself. This means from within our template we can call methods directly on the exception object.

Let’s take a quick look at a snippet from our error.ftl template to highlight this:

<body>
    <h1>Error - ${model.message}!</h1>
</body>

In our final example, we’ll take a look at a simple unit test:

@Test
public void givenGetFruitByName_whenFruitUnknown_thenErrorTemplateInvoked() {
    String response = target("/fruit/orange").request()
      .get(String.class);
    assertThat(response, containsString("Error -  Fruit not found: orange!"));
}

In the above example, we use the response from our fruit resource. We check the response contains the message from the IllegalArgumentException that was thrown.

5. Conclusion

In this article, we’ve explored the Jersey framework MVC extension.

We started by introducing how MVC works in Jersey. Next, we took a look at how to configure, run and set up an example web application.

Finally, we looked at three ways of using MVC templates with Jersey and Freemarker and how to handle errors.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)