Get to Know Jakarta MVC

To help you get to know the Jakarta MVC specification, here’s a recap of its history and status, and a brief introduction to the technology.

Jakarta MVC History and Status

The story of Jakarta MVC started back in 2014 when Java Specification Request (JSR) 371 was proposed in the Java Community Process. The work progressed very well, and the specification became popular in the community as a frequently requested addition to Java EE. When the specification was dropped for Java EE 8, the community took over and released MVC 1.0 as an independent specification in January 2020. After this release, it was transferred to the Eclipse Foundation and renamed to Jakarta MVC. 

Jakarta MVC 1.1 was released in September 2020 under the Eclipse Foundation Specification License. Just three months later, in December 2020, Jakarta MVC 2.0 was released with the jakarta.mvc.* namespace and aligned with Jakarta EE 9.

Jakarta MVC 2.0 is the most recent version of the specification, and there are currently two compatible implementations: 

Work on Jakarta MVC 2.1 is ongoing, and it is expected to be released in the Jakarta EE 10 timeframe. The Jakarta MVC project will continue to seek inclusion in the Jakarta EE Web Profile

MVC Styles 

In the Model-View-Controller (MVC) design pattern, the controller responds to a request by updating the model and selecting which view to display. The view then retrieves the data to display from the updated model (Figure 1).

MVC-1
Figure 1: Model-View-Controller Relationships

This widely used design pattern can be used in two ways: component-based and action-based. 

Component-Based MVC

Component-based MVC is made popular by component frameworks, such as Jakarta Server Faces. In this style of MVC, the framework provides the controller. This allows application developers to focus on implementing models and views, leaving controller logic to be handled by the framework (Figure 2).

MVC-2
igure 2: Component-Based MVC


Action-Based MVC

In the action-based style of MVC, the application defines the controller, giving application developers a little more fine-grained control (Figure 3).

MVC-3
Figure 3: Action-Based MVC


Jakarta MVC is an action-based MVC framework, which makes it complementary to the component-based MVC framework provided by Jakarta Server Faces. Other examples of action-based MVC include Spring MVC and Apache Struts.

Jakarta MVC Basics

Jakarta MVC is built on top of Jakarta RESTful Web Services. That means everything you know about Jakarta RESTful Web Services can be applied to your Jakarta MVC application as well.

Let’s take a closer look at what you can do with Jakarta MVC. 

The Controller

The @Controller annotation defined by Jakarta MVC marks a resource as the controller. If the annotation is applied to the resource class, all resource methods in the class become controllers. 

@Controller
@Path("hello")
public class Hello {
 
    @Path("one")

    public String oneController() {
    }

    @Path("another")
    public String anotherController() {
    }
}

The annotation can also be applied to a specific resource method. This approach is useful if you want to combine MVC controllers with REST resources in the same class.

@Path("hello")
public class Hello {

    @Controller
    @Path("one")
    public String oneController() {
    }

    @Controller
    @Path("another")
    public String anotherController() {
    }
 
    @Path("not-a-controller")
    public String notAController() {
    }
}

There are three ways to define which view a controller should select in a Jakarta MVC application:

  • First, if a controller returns void, it must be decorated with an @View annotation 
  • Second, a String returned is interpreted as a view path
  • Third, a Jakarta RESTful Web Services Response object where the entity is one of the first two 

The example below illustrates all three approaches.

@Controller
@Path("hello")
public class HelloController {

    @GET @Path("void")
    @View("hello.jsp")
    public void helloVoid() {
    }

    @GET @Path("string")
    public String helloString() {
        return "hello.jsp";
    }

    @GET @Path("response")
    public Response helloResponse() {
        return Response.status(Response.Status.OK)
            .entity("hello.jsp")
            .build();
    }
}


That’s all there is to the controller in Jakarta MVC. The rest is exactly as you know from Jakarta RESTful Web Services, such as how to handle and validate path parameters, query parameters, and bean parameters.

The Model

Jakarta MVC supports two ways of handling models:

  • Use any CDI @Named beans as your model
  • Use the provided Models interface as your model

For the CDI approach, you simply inject the CDI @Named bean into the controller, update it as needed, and return the view, as shown in the example below.

@Named("greeting")
@RequestScoped
public class Greeting {
    private String message;
    // getters and setters
}

@Path("hello")
public class HelloController {

    @Inject
    private Greeting greeting;

    @GET
    @Controller
    public String hello() {
        greeting.setMessage("Hello there!");
        return "hello.jsp";
    }
}

If the view model does not support CDI, or you want to use the provided Models interface for a different reason, you can inject the Models map and update it as shown below.

@Path("hello")
public class HelloController {

    @Inject
    private Models models;

    @GET
    @Controller
    public String hello() {
        models.put("string_greeting", "Howdy!");
        return "hello.jsp";
    }
}

The View

Views in Jakarta MVC applications are processed by a mechanism called view engines. View engines for Jakarta Server Pages and Facelets must be supported by all implementations, although the requirement to support Facelets is likely to be removed in future versions of Jakarta MVC. Additional view engines can be added using a well-defined CDI extension mechanism.

In Jakarta Server Pages views, the model is available using the Jakarta Expression Language, as shown in the example below.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>
        <h1>${greeting.message}</h1>
        <h1>${string_greeting}</h1>
    </body>
</html>

The rendered view would look something like this:

Hello   
Hello there!
Howdy!

Advanced Jakarta MVC Topics

The Jakarta MVC specification document provides a very good overview of what’s included in Jakarta MVC. I introduce some of the items here, but please refer to the specification document for details.

Data Binding

Jakarta MVC extends the data binding provided by Jakarta RESTful Web Services with support for internationalization and handling of binding errors within the controller. The Jakarta MVC-specific data binding is enabled by adding the @MvcBinding annotation to the relevant field or method parameter. Binding errors are handled in the controller by injecting BindingResult and using it to handle the error before the next view is rendered. 

@Controller
@Path("form")
public class FormController {

    @MvcBinding
    @FormParam("age")
    @Min(18)
    private int age;

    @Inject
    private BindingResult bindingResult;

    @POST
    public String processForm() {

        if( bindingResult.isFailed() ) {

            // handle the failed request
        }
 

        // process the form request
    }
}

Security

Jakarta MVC provides support to protect applications from Cross-Site Request Forgery (CSRF). To provide this support, the Jakarta MVC implementation generates a CSRF token that is available via the MvcContext object. To verify a request, simply add the @CsrfProtected annotation to the controller, as shown below.

@Path("csrf")
@Controller
public class CsrfController {

    @GET
    public String getForm() {
        return "csrf.jsp"; // Injects CSRF token
    }

    @POST
    @CsrfProtected // Required for CsrfOptions.EXPLICIT
    public void postForm(@FormParam("greeting") String greeting) {
        // Process greeting
    }
}

Events

Jakarta MVC specifies a number of events that occur while processing requests. The event mechanism is based on Jakarta Contexts and Dependency Injection (CDI), and can be observed using the @Observer annotation defined by Jakarta CDI.

Internationalization

Jakarta MVC uses the term “request locale,” which can be used for locale-dependent operations. Example use cases for locale-dependent operations include data binding, data formatting, and language-specific validation error messages. The request locale is available through the MvcContext object.

@Controller
@Path("/foobar")
public class MyController {

    @Inject
    private MvcContext mvc;

    @GET
    public String get() {
        Locale locale = mvc.getLocale();
        NumberFormat format = NumberFormat.getInstance(locale);
    }
}

For more insight into Jakarta MVC:

Learn More About Jakarta MVC and Get Involved

We welcome everyone who would like to get involved in Jakarta MVC. To discover the many different ways you can contribute to the project, click here.

This article was first published in the Eclipse Newsletter, November 29, 2021.

Hashtag Jakarta EE #101

Welcome to issue number one hundred and one of Hashtag Jakarta EE!

There is an interesting discussion around Java SE 17 support in Jakarta EE going on the Jakarta EE Community mailing list. As you probably are aware, the upcoming Jakarta EE 10 release will raise the API source- and binary levels to Java SE 11. Does this mean that Jakarta EE doesn’t support Java SE 17?

Absolutely NOT! The key is the + in TCK run with: Java SE 11+ in the image below.

There are already several compatible implementations certified with Java SE 17 for Jakarta EE 9.1. And I would say it is a pretty safe bet that all of these, as well as others, will be certified on Java SE 17 for Jakarta EE 10 as well. So it is safe to say that Jakarta EE supports Java SE 17, even if the APIs aren’t incorporating any language features introduced after Java SE 11.

When we look beyond Jakarta EE 10, the plan is to raise the baseline to Java SE 17. So here is a question for the community: Which language features available in Java SE 17 make sense to build into the APIs, and for which specification?

Next week is all about JakartaOne Livestream. Join us there to learn more about Jakarta EE and much more from an amazing lineup of speakers. Tanja and I will also host Studio Jakarta EE between the sessions with lots of interesting content you don’t want to miss!

Hashtag Jakarta EE #100

Welcome to the hundredth issue of Hashtag Jakarta EE!

Is it number 100 already? I started the Hashtag blog series as an experiment to see if I could establish a drum beat with weekly updates from the Jakarta EE community. By reaching 100 consecutive weekly posts, I think I have succeeded in that. Now, let’s look forward and see if we can reach a thousand…

JakartaOne Livestream 2021 is only one week away. The third edition of this annual online event is an excellent opportunity to keep up with what’s going on in and around the Jakarta EE community. Check out this amazing list of speakers!

The work with Jakarta EE 10 is chugging along. A couple of new pull requests for release reviews have appeared. Currently,  Jakarta JSON Processing 2.1Jakarta RESTful Web Services 3.1Jakarta Expression Language 5.0Jakarta Mail 2.1Jakarta Activation 2.1, Jakarta Servlet 6.0, and Jakarta Server Pages 3.1 have created pull requests to initiate their release reviews. There are quite a few still missing and the clock is ticking toward December 15, which is the date the Jakarta EE Platform project has requested the release reviews to start. If you are involved in any of these specification projects, please help get them over the finishing line.

I have had a couple of weeks with traveling and in-person events. It has been absolutely awesome to actually meet people again! Let’s keep our fingers crossed and hope the trend of going back to in-person events continues. There are quite a few in the pipeline for next year. Until then, make sure to sign up for the greatest Jakarta EE online event of the year: JakartaOne Livestream 2021.

Hashtag Jakarta EE #99

Welcome to the ninety-ninth issue of Hashtag Jakarta EE!

The pull requests used to initiate release reviews by the Jakarta EE Specification Committee for Jakarta EE 10 have started appearing. Check out the specification you are interested in to see if you can do anything to help get it over the finishing line. Currently, there are pull requests for Jakarta JSON Processing 2.1, Jakarta RESTful Web Services 3.1, Jakarta Expression Language 5.0, Jakarta Mail 2.1, and Jakarta Activation 2.1.

Another topic that is being discussed in the Jakarta EE Platform project lately is to tighten up the language around the @Priority annotation. The intention is to have a consistent way of determining priorities across the specifications using the annotation. What it boils down to is this: Should a higher number mean higher priority? Or should the lower number have higher priority, thus sorted in ascending order?

You can read all the details in the proposal document and give your input in this survey.

My personal opinion on this topic is that there should be one way of doing this, and it should be consistent throughout the platform (Option Ax or Bx). I don’t want to introduce any new annotations to bypass the problem (Option C), and doing nothing (Option E)is just as bad. I guess I would prefer HIGHER number means HIGHER priority (Option Ax), but with be comfortable with the opposite as well, i.e. LOWER number means HIGHER priority (Option Bx).

Java on Rails

This week, I was on the road (or on rails actually) with Simon Ritter, Mattias Karlsson, and Jeanne Göthberg. We did a tour of three Swedish JUGs in three days. First Malmö, then Gothenburg, and finally Stockholm. We had great fun, three successful events, and great conversations. It felt really good to be out meeting the community again. This was the first in-person event for all the three JUGs in a while.

On stage after my talk on the last day, Mattias announced that I got a Jakarta EE talk accepted for Jfokus 2022. The conference is fully booked, but there is a waiting list if you haven’t gotten hold of your ticket yet. See you in Stockholm in February next year!

JakartaOne Livestream is coming up in a couple of weeks! Register for this free, one-day virtual event now!

Last year, we had a cake theme, where we encouraged everyone to bake a cake and submit pictures to win great prizes. Before that, we had a cupcake theme. This year, we are going for PIZZA!

I am looking forward to seeing the creative spins on this challenge. I guess I could make the yellow and orange colors of the Jakarta EE sailing ship with some looks-like-cheese-melts-like-cheese-certainly-doesn-t-taste-like-cheese kind of substance, but how to get the blue color on a pizza that is still possible to digest goes beyond my cooking skills. Writing Jakarta EE with pepperoni is as far as my creativity goes.

Hashtag Jakarta EE #98

Welcome to the ninety-eighth issue of Hashtag Jakarta EE!

JakartaOne Livestream 2021 is just a couple of weeks away. I know that having a virtual conference is not that unique nowadays, but when we did the first edition of JakartaOne Livestream back in 2019, it was somewhat unchartered territory. It was an immediate success that was followed up in 2020. In the 2020 edition, we brought in the concept of having 15-minute long Studio Jakarta EE sessions between the regular talks. These were a mix of technical and non-technical short talks as well as interviews.

This year, we are going one step further with Studio Jakarta EE. It is still in the concept phase, but I am confident it will be amazing!

Even if you are suffering from zoom fatigue and pretty fed up with online conferences by now, please do register for JakartaOne Livestream 2021. If you’re still not convinced, look at the amazing lineup of speakers we have for this year!

Jakarta EE 10 is moving forward. The pull requests used to initiate release reviews by the Jakarta EE Specification Committee have started appearing. Check out the specification you are interested in to see if you can do anything to help get it over the finishing line.

From discussions on the Jakarta EE Platform mailing list and weekly calls, it has become apparent that there is a need to handle common APIS, functionality, libraries, and such to ensure consistency between the specifications. Thus, there is a proposal for a Jakarta Commons project being worked on. Take a look and let us know what you think!

Hashtag Jakarta EE #97

Welcome to the ninety-seventh issue of Hashtag Jakarta EE!

This week was a flashback of the past, a return to normal, and a promise of the future! First, I traveled to London, UK to speak at Devoxx UK where I presented Jakarta EE Core Profile – A Slimmer Jakarta EE. It was awesome to meet so many community members and hang around with them in the exhibition hall and at dinner parties. 

I then continued to the Netherlands and J-FALL. This was an even bigger conference with 1300 attendees onsite at the venue. My talk about Jakarta EE 10 was well received.

I even met Duke there. A slightly smaller version than the Duke that used to roam the corridors of JavaOne, but Duke is Duke…

The work with Jakarta EE 10 continues. There are a couple of specifications that have started preparing pull requests for their release reviews. One of the tasks associated with Jakarta EE 10 is to establish JPMS Module Names for all the specifications. See Jakarta EE Project Names and Codes for an overview of policy around the module names.

I am spending the upcoming week at home, but after that, I will be traveling again. This time a three-day tour of the major Java User Groups in Sweden. The tour is called Promising Future with Java 17 and the schedule looks like this:

November 16: Malmö
November 17: Gothenburg
November 18: Stockholm

If you are located in any of these cities, do sign up for this event. Looking forward to meeting you there!

Hashtag Jakarta EE #96

Welcome to the ninety-sixth issue of Hashtag Jakarta EE!

Last week was pretty busy with everything happening at EclipseCon 2021.

The Jakarta EE Community Day on Monday featured a packed schedule full of amazing content with Reza Rahman being the perfect host throughout the day. On Tuesday, I participated in a roundtable discussion where we discussed Java as the ideal language for cloud-native applications, and on Wednesday I had my talk Jakarta EE 9 and Beyond where I put the emphasis on the Beyond part.

This week, I am going on the road, or more precisely put; in the air, or up with the clouds (no pun intended at all 😉 ).

The first part of the week will be spent in London attending and speaking at Devoxx UK. My talk is titled Jakarta EE Core Profile – A Slimmer Jakarta EE and will be on Tuesday at 14:30 GMT. Devoxx UK is a hybrid conference this year, so you will be able to attend virtually if you are unable to make it in person.

After London, I am going to Holland for J-FALL. This year’s conference is back to being on-site. My talk at J-FALL this year is titled Jakarta EE 10 is Coming Your Way!. In this talk, I will give an update of what to expect from Jakarta EE 10.

While I am touring Europe, the work with Jakarta EE 10 continues. There are quite a few specifications expected to start their release reviews by the Jakarta EE Specification Committee this week. If you are involved in any of the Jakarta EE specification projects, please take a look at the Release Review section of the JESP Guide for a simple overview of what is expected according to the Jakarta EE Specification Process (JESP).

Hashtag Jakarta EE #95

Welcome to the ninety-fifth issue of Hashtag Jakarta EE!

Next week is the week of EclipseCon 2021.

EclipseCon 2021 is a four-day online conference, and it is 100% free! It is packed with content that should cater to anyone. Check out the schedule for your pick! I’ll focus on the content specific to Jakarta EE here. The conference starts on Monday with the Jakarta EE Community Day.

SessionTime (CET)Speakers
Jakarta EE Community State of the Union15:00 – 15:50Tanja Obradovic, Ivar Grimstad, Will Lyons
MicroProfile Community Current and Future16:00 – 16:50Emily Jiang
What’s Coming to Jakarta Security17:00 – 17:50Arjan Tijms
Jakarta Concurrency Futures18:00 – 18:50Steve Millidge
Jakarta REST: Looking Ahead19:00 – 19:50Andy McCright
Jakarta NoSQL and the Future of Polyglot Persistence in Java20:00 – 20:50Otavio Santana
Jakarta EE Community Day Schedule

The main part of the conference is from Tuesday to Thursday. Take a look at all the talks related to Jakarta EE. Specifically, I would like to point you to my session Jakarta EE 9 and Beyond on Wednesday 27 at 13:50 CET.

The focus of the talk will be the Beyond part. And what comes after 9…? Well, we did deliver a 9.1, actually, but what I am aiming at here is Jakarta EE 10. I will provide a sneak peek into the content of Jakarta EE 10. I will also show different options of how to get from the previous versions to 9, 10, and Beyond. Who knows, maybe I will throw in a demo of how to use Java 17 features with Jakarta EE.

Talking about Java 17, I have the pleasure of going on tour with Simon Ritter. In three days, we will cover the three major Java User Groups in Sweden:

November 16: Malmö
November 17: Gothenburg
November 18: Stockholm

If you are located in any of these cities, do sign up for this event. Looking forward to meeting you there!

Hashtag Jakarta EE #94

Welcome to the ninety-fourth issue of Hashtag Jakarta EE!

Jakarta EE 10 is entering a new phase!

The release reviews for the individual specifications are about to start. The release reviews are expected to be conducted over the following months, and hopefully, be concluded by the end of the Year. Check out the Pull Requests for release reviews to follow the progress as they start coming in.

First in-person conference since February 2020 – check!

Arriving at the airport in Gdańsk on my way to Infoshare 2021, I bumped into Sebastian. Just like the old times!
In my talk, A Closer Look at Jakarta EE 10, I gave an overview of what to expect from Jakarta EE 10 and how to migrate from earlier versions. I even threw in a demo of how to use Java 17 records with Jakarta EE.

If you haven’t registered for EclipseCon 2021 yet, I recommend that you do. It is a 100% free online conference packed with content. Specifically, check out the Jakarta EE talks.

Hashtag Jakarta EE #93

Welcome to the ninety-third issue of Hashtag Jakarta EE!

This week, I had the pleasure of speaking at JCON 2021. Two talks, actually: Jakarta EE Core Profile – A Slimmer Jakarta EE and Jakarta EE Security – Sailing Safe in Troubled Waters. The last one co-speaking with Werner Keil. Even with a computer crash just as the live demo was about to start, I think it went pretty well.

Next week, I am going to Infoshare 2021 in Gdańsk, Poland for my first in-person conference since February 2020. My talk titled A Closer Look at Jakarta EE 10 will give an overview of what to expect from Jakarta EE 10, how to migrate from earlier versions, and how to leverage Java SE 17 features in your Jakarta EE applications.

JakartaOne Livestream 2021 is coming up in December. The program committee has reviewed the abstracts and speaker acceptance notices have started, and the program will be announced pretty soon. Until then, make sure to register for the conference. You don’t want to miss this one!


The 2021 JCP Community Virtual Gathering and Awards is held on October 12, 1-3 pm PDT. Register here to participate in the celebration of the community with the JCP Program.