The “V” in MVC: In the Model-View-Controller (MVC) architectural pattern, the View is responsible for presenting data to users, defining the user interface, and handling how information is exchanged (displayed and input).
Thymeleaf: In the world of Java EE Web development, we run into many solutions to help us build up HTML views:
JSP – Jakarta Server Pages, formerly JavaServer Pages, helped us write HTML with custom tags to build a good UI. The end result is a bunch of HTML documents with special tags that let us programmatically fill in content, meaning they’re templates, and JSP as a template engine can resolve them. Unfortunately, it’s very old, slow, difficult to debug and leaves a lot to be desired.
JSF – Jakarta Server Faces, formerly JavaServer Faces, is a component-based framework building on top of JSP for building reusable UI component and connecting to data sources, making our lives much easier. Still, it is complex and not easy to integrate with Spring MVC.
Thymeleaf – Spring MVC’s default template engine of choice, it is a better, more modern alternative to JSP, but largely does the same thing (allows us to write HTML templates that Thymeleaf, as a template engine, will resolve, resulting in dynamically generated webpages when the user requests them).
Illustrating an overview of the architecture of a full-stack Spring application, with focus on the View layer, with example documents home.html, restaurant-list.html and about-us.html.
👩💻 Hands-on Demo: Add Thymeleaf
Since Spring encourages decoupled flexibility, and we can use any templating engine we want, we need to add the Thymeleaf dependency to get cracking with it.
Note: When using Spring Initializr to create a new Spring MVC project, if you know beforehand you’re gonna use Thymeleaf, you can just add it while “shopping” for dependencies, you’ll find it under Template Engines.
In Summary: a View is simply a file with code that describes what the presentation should look like. In web apps and specifically Spring MVC, it’s a .html file that isn’t 100% pure HTML – it contains some custom tags that help us make programmable/smart templates that your web browser will not understand, which, when resolved by a template engine like Thymeleaf, will get programmatically filled in by data, resulting in a freshly generated HTML web page that can be presented to the user.
How to Make Views in Spring MVC (with Example)
By default, Spring MVC’s View Resolver will search for views in our “templates” folder on the classpath, which you can find under src/main/resources/templates (remember Spring Boot automatically loads everything in the resources folder to the classpath).
So, to start creating our first View, we need to create the “templates” directory if it doesn’t already exist.
Then, we start making View files. For Thymeleaf, it’s sufficient to simply start creating files in here with the .html extension.
Your IDE might let you simply create HTML files based on templates for a more speedy start.
We recommend using kebab-casing or camelCasing for your templates’ file names.
Since we’ll be using a lot of Thymeleaf-specific custom HTML tags and expressions, let’s add the Thymeleaf namespace to the <html> opening tag:
Finally, you can start filling in the HTML to your heart’s content to build up the user interface.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello Spring MVC</title>
</head>
<body>
<h2>Say Hello to...</h2>
<h1>Spring MVC</h1>
<img th:src="@{/img/logo.png}" alt="" srcset="">
<p>This is my very first Spring MVC web app!</p>
</body>
</html>
Observations
Immediately something new jumps out at you, namely the th: attribute (in this case th:src). This is a special Thymeleaf attribute, and basically tells Thymelaf “No, this isn’t a normal hardcoded src, this is an src I want you (Thymeleaf) to dynamically resolve when generating the webpage.”
In this example, the dynamic source attribute is telling Thymeleaf to resolve the app’s root directory, with the relative path added on, to find the image (it’s useful to do this, instead of hardcoding a path, in case the location of the app on the webserver ever changes).
In the case of Spring MVC, the root directory for static things like images and CSS files is the “src/main/resources/static” folder:
We decided to put the image in its own “img” folder, that way we can organise our files better, but it’s not mandatory.
Later on, we will have other folders and files, for example a “css/styles.css” stylesheet file and a “img/favicon.ico” icon file.
👩💻 Hands-on Demo: Views in Spring MVC
We’re going to continue on our exploratory Hello Spring MVC project and make our very first view!
In the “hello-spring-mvc” project from a previous demo, create a view that represents the home page.
In the appropriate folder, create a new HTML-file and give it a name that corresponds to the returned String in our controller method from a previous demo.
To the HTML code, add the necessary namespace attributes to the opening html tag.
Start creating a rudimentary home page (no CSS yet), with headings, images and paragraphs.
Add an image representing your app’s logo to the appropriate folder used for static files like images, CSS, JS, etc.
To the HTML code, add an image element that makes a dynamically resolved reference to the logo image by using Thymeleaf’s th:src attribute instead of the vanilla src.
Run your web app and navigate to the home page in the web browser.
Solutions
🕵️♂️ Click here to reveal the solutions
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello Spring MVC</title>
</head>
<body>
<h2>Say Hello to...</h2>
<h1>Spring MVC</h1>
<img th:src="@{/img/logo.png}" alt="" srcset="">
<p>This is my very first Spring MVC web app!</p>
</body>
</html>
The Full Picture So Far…
Let’s zoom out a bit and overview the bigger picture to understand the whole story a bit better, now that we understand the role of our View.
Do you remember our HomeController-class?
@Controller
public class HomeController {
@GetMapping("")
public String getHomePage(){
return "home";
}
}
Notice the return "home".
The "home" is a reference to the name of our view, home.html.
Spring MVC’s View Resolver is smart enough to know that return "home" means it needs to look for an HTML file in the templates folder called home.html (we don’t need to add the folder name or .html extension to the returned String).
Thanks to this getHomePage()-method, which is mapped to a GET-request sent to the empty relative path (i.e. www.example.com/), a user will from now on be able to navigate to the home page of our web app, and be able to see our home.html view, which will be freshly generated upon request.
👩💻 Hands-on Demo: Views in Spring MVC (Part 2)
To practise everything we’ve seen, let’s make a new page for our user to interact with the “About Me” page.
Create a new view called “about-me.html“, with some rudimentary info about you.
Add a photo of yourself which is saved locally on the server.
Add another image (for example of your favourite sport, meal, etc.) which is externally stored and referenced without the need for Thymeleaf.
In the HomeController-class, write a new method that listens to GET-requests sent to "/about", and returns the name of your newly created view.
Rerun your web app and, in your web browser, navigate to localhost:8080/about and see your new view in action.
@Controller
public class HomeController {
...
@GetMapping("about")
public String getAboutMe(){
return "about-me";
}
}
We will look at the much more interesting things Thymeleaf can do to create truly dynamic web pages in a later topic.
Summary
The “V” in the Model-View-Controller (MVC) architectural pattern represents the View, responsible for presenting data, defining the user interface, and information exchange.
Java EE Web development offers various view-building solutions, including JSP (Jakarta Server Pages), JSF (Jakarta Server Faces), and Thymeleaf.
Spring MVC uses Thymeleaf as its default template engine for creating dynamic web views.
Views in Spring MVC are stored in the “templates” directory, typically located under “src/main/resources/templates.”
When creating Spring MVC views, include the Thymeleaf namespace declaration in the HTML <html> opening tag to use Thymeleaf-specific attributes and expressions.
Thymeleaf uses custom attributes like th:src for dynamic resource resolution and HTML content generation.
In Spring MVC, the root directory for static resources (images, CSS, etc.) is “src/main/resources/static.”
Spring MVC’s View Resolver automatically searches for views with names corresponding to the Strings returned by controller methods (e.g., return "home" corresponds to “home.html”).
Views created with Thymeleaf are dynamically generated upon user request, making them a powerful tool for building modern, dynamic web applications.
We gebruiken cookies op onze website om u de meest relevante ervaring te bieden door uw voorkeuren en herhaalde bezoeken te onthouden. Door op "Alles accepteren" te klikken, stemt u in met het gebruik van ALLE cookies. U kunt echter "Cookie-instellingen" bezoeken om een gecontroleerde toestemming te geven.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duur
Omschrijving
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.