Spring MVC view layer- Thymeleaf vs. JSP

In this tutorial we will describe about two view layers for Spring MVC. One is JSP and another is Thymeleaf. Here we will compare the same page (a subscription form) created twice for the same Spring MVC application: once using Thymeleaf and another time using JSP, JSTL and the Spring tag libraries.

Common requirements-
Our customers need a form for subscribing new members to a message list, with two fields:
  • Email address
  • Type of subscription
Our application will have two @Controllers, which will contain exactly the same code but will forward to different view names:


  • SubscribeJsp for the JSP page (the subscribejsp view).
  • SubscribeTh for the Thymeleaf page (the subscribeth view).


We will have the following classes in our model:


  • Subscription form-backing bean with two fields: String email and String type.
  • Type has values EMAILS and DAILY_DIGEST.
Doing it with JSP



And this is our JSP code, making use of both JSTL (core) and Spring (tags and form) JSP tag libraries:

SubscribeJsp.jsp

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
 
<html>
 
  <head>
    <title>Spring MVC view layer: Thymeleaf vs. JSP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" href="<s:url value='/css/thvsjsp.css' />"/>
  </head>
 
  <body>
 
    <h2>This is a JSP</h2>
 
    <s:url var="formUrl" value="/subscribejsp" />
    <sf:form modelAttribute="subscription" action="subscribeMe">
 
      <fieldset>
 
        <div>
          <label for="email">Email: </label>
          <sf:input path="email" />
        </div>
        <div>
          <label>Type: </label>
          <ul>
              <li>
                <sf:radiobutton path="type" value="Email" />
                <label for="subscriptionType1">
                  All emails
                </label>
              </li>
              <li>
                <sf:radiobutton path="type" value="Digest" />
                <label for="subscriptionType2">
                  All Digests
                </label>
              </li>
          </ul>
        </div>
 
        <div class="submit">
          <button type="submit" name="save">SUBSCRIBE ME</button>
        </div>
 
      </fieldset>
 
    </sf:form>
 
  </body>
 
</html>

Doing it with Thymeleaf


And this is our Thymeleaf code:

SubscribeTh.html

<!DOCTYPE html>
 
<html xmlns:th="http://www.thymeleaf.org">
 
  <head>
    <title>Spring MVC view layer: Thymeleaf vs. JSP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all"
      href="../../css/thvsjsp.css" th:href="@{/css/thvsjsp.css}"/>
  </head>
 
  <body>
 
    <h2>This is a Thymeleaf template</h2>
 
    <form action="#" th:object="${subscription}" th:action="@{/subscribeth}">
 
      <fieldset>
 
        <div>
          <label for="email">Email: </label>
          <input type="text" th:field="*{email}" />
        </div>
        <div>
          <label>Type: </label>
          <ul>
            <li>
              <input type="radio" th:field="*{type}" th:value="email" />
              <label>All emails</label>
            </li>
            <li>
              <input type="radio" th:field="*{type}" th:value="digest" />
              <label>All Digest</label>
            </li>
            <li th:remove="all"><input type="radio" /> <label>Second Type</label></li>
          </ul>
        </div>
 
        <div class="submit">
          <button type="submit" name="save">Subscribe me!</button>
        </div>
 
      </fieldset>
 
    </form>
 
  </body>
 
</html>

Things to notice here:
  • This looks much more HTML-ish than the JSP version – no strange tags, just some meaningful attributes.
  • Variable expressions (${...}) are Spring EL and execute on model attributes, asterisk expressions (*{...}) execute on the form backing bean, hash expressions (#{...}) are for internationalization and link expressions (@{...}) rewrite URLs. (If you want to know more about this, have a look at the “Getting started with the Standard Dialect in 5 minutes” guide).
  • We are allowed to have prototype code there: for example, we can set an Email: text in the label for the first field, knowing that Thymeleaf will substitute it with the internationalized text with key subscription.email when it executes the page.
  • We have even been able to add anfor a second radiobutton just for prototyping pleasure. It will be removed when Thymeleaf executes our page.

Change the page style--

Let’s see the steps we would have to take with each technology:

Changing the page style using JSP

Step 1: Deploy the application into our development server and start it up. Our JSP page will not render without starting the server, so this will be a requirement.

Step 2: Navigate through the pages until we find the one to change. Normally, the page to change will be one among several dozen pages in our application, and it is quite possible that in order to reach it we will need to click links, submit forms and/or query databases.

Step 3: Fire up firebug, dragonfly, or our favourite in-browser web development tool. This will allow us to modify our styles acting directly on the browser’s DOM, and thus see immediate results.

Step 4: Make the colour changes. Probably trying a couple of different tones of blue before deciding on the one we like.

Step 5: Copy-paste the changes into our CSS files.

Changing the page style using Thymeleaf

Step 1: Double-click on the .html template file itself and let our browser open it. Being a Thymeleaf template, it will show just fine, only with template/prototype data.

Step 2: Open the .css file with our favourite text editor. The template file statically links to the CSS in its tag (with an href that Thymeleaf substitutes when executing the template by the one generated by th:href). So any changes we make to that CSS will be applied to the static page our browser is displaying.

Step 3: Make the colour changes. As was the case with JSP, we will probably have to try several colour combinations, which will be refreshed in our browser just by pressing F5.

The difference in the number of steps is not really important here (we could also have used firebug with the Thymeleaf template). What is really important is the complexity, the effort and the time required by each of the steps required for JSP. Having to deploy and start the whole application made JSP just lose.

What’s more: think of how this difference would evolve if:

  • Our development server was not local but remote.
  • Changes didn’t involve only CSS but also adding/removing some HTML code.
  • We still hadn’t implemented the required logic in our application to actually reach that page once deployed.

Pros and Cons in JSP

Standard Tags have many benefits:


  • I can use them to do much more than just externalizing layout information. In the end, they can easily make your JSPs 5 times smaller than they would be otherwise.
  • Eclipse/STS works well with custom tags so you’re able to use CTRL+space for auto-completion.

On the down side:


  • Documentation is not the best.
  • Even though custom tags are pretty neat already, I can’t recall any improvement to them in the past few years.
  • Using Custom tags implies that you’re using a JSP Engine inside your web container. You can then expect some minor differences depending on the web container you’re using (Apache Tomcat, IBM Websphere, Oracle Weblogic…).
  • It is also harder to Unit Test your view layer. You can see Spring MVC Test framework if you’re interested in this topic.

Pros and Cons in Thymeleaf

On the bright side:

  • ThymeLeaf is a healthy open source project: new features coming up each month, good documentation, responsive user forums…
  • It is the ideal template engine if you want your web designer to be able to read your view files
  • The Expression Language used (actually called Standard Dialect) is much more powerful than JSP Expression Language.
  • Unlike JSPs, Thymeleaf works well for Rich HTML emails (see http://www.thymeleaf.org/springmail.html).

On the down side:

  • Thymeleaf does not have an equivalent to custom tags (.tagx files) yet.
  • At this stage, ThymeLeaf is not compatible with JSP tag libraries.

Conclusion


We’ve seen the JSP and Thymeleaf approaches side by side. If your application uses hundreds of JSPs, we are not saying that you should ditch them all and start over again using Thymeleaf. However you might consider Thymeleaf for HTML pages outside of the web container such as for Rich HTML emails.

If you are starting on a new project, we strongly encourage you to compare both Thymeleaf and JSPs in order to figure out which one is more suitable to your needs.




No comments:

Post a Comment