How to create a Spring Boot Web Application (Spring MVC with JSP/ThymeLeaf)

In this tutorial, you will learn how to create a Spring Boot project for developing a Java web application with Spring MVC and JSP/ThymeLeaf, running in an embedded Tomcat server. The sample project in this tutorial is developed with JDK 8 and Eclipse IDE Oxygen with Maven.

If you ever developed Spring MVC applications before Spring Boot’s times, you know that it requires writing pretty much boiler-plate code just for the configuration which you use the same for almost projects. This repeated and boring task consume programmer’s time which should be spent on developing business logic for the application.

And now with Spring Boot, things get a lot easier. All the configurations are automatically done for you (auto configuration) with sensible defaults. So you can quickly jump on coding the business logic without worrying about the configuration details.

Now, let follow this tutorial, step by step, to understand how to use the sensible defaults when developing a Spring MVC web application with JSP/ThymeLeaf.

Table of Content:

1. Create Spring Boot Project in Eclipse

You need to generate a Spring Boot project using Spring Initializr web tool and then import in Eclipse.

Go to https://start.spring.io/. By default, the project type is Maven with Java and Spring Boot stable version (2.0.4). Enter the project metadata (Group and Artifact) and choose the Web dependency as shown in the following screenshot:

Spring Boot Project Initializr

Click Generate Project to download the generated project as a Zip file, say SpringBootWebAppExample.zip . Extract it to your Eclipse’s workspace directory.

In Eclipse, click File > Import… In the Import dialog, select General > Projects from Folder or Archive, and click Next. In the next screen, click Directory… to browse the directory you have extracted, and then Eclipse detects the project to be imported as Maven:

Import project

Click Finish and you may have to wait for a while, when Eclipse is updating the Maven project, i.e. downloading JAR files of the dependencies. Then you can see the project has the following initial structure:

intial project structure

Open the pom.xml file to see Maven dependencies. You see it’s very simple, there are only two dependencies declared:

  org.springframework.boot spring-boot-starter-web  org.springframework.boot spring-boot-starter-test test  

The dependency spring-boot-starter-web enables web development with Spring MVC and embedded Tomcat server. It requires all common dependencies (Spring framework, logging, validation, JSON, …) with proper versions so you don’t have to struggle with a lot of dependencies and their versions like normal Spring MVC application development.

You can remove the dependency spring-boot-starter-test if you don’t use tests. When doing so, also delete the test class Spring-Boot-Web-App-Example-Application-Tests.java (no hyphens) under src/test/java directory.

Expand the Maven Dependencies folder to see various JAR files required by the project, and the good thing is you don’t have to do anything to configure this. Spring Boot includes all these defaults.

Spring-Boot-Web-App-Example-Application.java (no hyphens) :this is the entry point class to run the application. It has the following code:

package net.codejava.SpringBootWebAppExample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootWebAppExampleApplication < public static void main(String[] args) < SpringApplication.run(SpringBootWebAppExampleApplication.class, args); >>

The @SpringBootApplication annotation does the magic work to start the embedded Tomcat server, configure Spring Dispatcher Servlet, etc.

And there are two default directories and one properties file in the src/main/resources folder.


2. Code default welcome page

If you have the static welcome page ( index.html ) for the application, put in under the src/main/resources/static directory. For example, create the index.html file with the following content:

    My Contacts - Spring Boot Web Application Example  

My Contacts

Click here to list all contacts

Now, let’s run the application by right-clicking in the code editor of the SpringBootWebAppExampleApplication class, click Run As > Java Application. You can see the application is started with Spring Boot logo and logging messages from Tomcat and Spring framework:

server started

Notice the last two lines in the Console view:

Tomcat started on port(s): 8080 (http) with context path '' Started SpringBootWebAppExampleApplication in 4.254 seconds (JVM running for 4.79)

By default, the server is listening on port number 8080 with empty context path, so type the following URL in your web browser:

http://localhost:8080/
Then you can see the welcome page gets displayed:

welcome page

You can override the default welcome page by creating a handler method in a Spring controller class like this:

@RequestMapping("/") public String welcome()

As you can see, this method handles requests with the URL pattern “/” which is the context root (home page) of the application, and it returns a view named “index” which is resolved to actual view page by Spring view resolver.

TIP: To increase productivity for Spring Boot project development, I recommend you to use Spring Boot DevTools for automatic restart.

3. Code Model, Business and Controller Classes

Suppose that when the user clicks the hyperlink Click here to list all contacts, the web application displays a list of contacts. Create the model class Contact as follows:

package net.codejava.SpringBootWebAppExample; public class Contact < private String name; private String email; private String country; public Contact() < super(); >public Contact(String name, String email, String country) < super(); this.name = name; this.email = email; this.country = country; >// getters and setters are excluded for brevity >

Next, create a business class that implements a method to return a hard-coded List of Contact objects like this:

package net.codejava.SpringBootWebAppExample; import java.util.ArrayList; import java.util.List; public class ContactBusiness < public ListgetContactList() < ListlistContact = new ArrayList<>(); listContact.add(new Contact("Marry John", "marry.john@gmail.com", "USA")); listContact.add(new Contact("Tom Smith", "tomsmith@outlook.com", "England")); listContact.add(new Contact("John Purcell", "john123@yahoo.com", "Australia")); listContact.add(new Contact("Siva Krishna", "sivakrishna@gmail.com", "India")); return listContact; > >

Next, create a Spring controller class to handle requests coming from the hyperlink in the welcome page above:

Name this class as AppController with the following code:
package net.codejava.SpringBootWebAppExample; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController < @RequestMapping("/list_contact") public String listContact(Model model) < ContactBusiness business = new ContactBusiness(); ListcontactList = business.getContactList(); model.addAttribute("contacts", contactList); return "contact"; > >

As you can see, this is standard Spring web controller class annotated with the @Controller annotation. The @RequestMapping("/list_contact") annotation specifies that the listContact() method is responsible to handle requests coming from the /list_contact URL.

This method uses the ContactBusiness class to get a List of Contact objects and puts this collection to a Model object, which will be then used by the view. Finally it returns the view name “contact”, which can be resolved to a JSP page or a ThymeLeaf template, depending on our configuration.

4. How to use JSP with Spring Boot

We will create JSP page with JSTL to display the contact list, so add the following two dependencies in the pom.xml file:

 org.apache.tomcat.embed tomcat-embed-jasper provided  javax.servlet jstl 

The dependency tomcat-embed-jasper is JSP Engine for Tomcat. It is required to enable JSP with Spring Boot.

By default, JSP pages are looked up inside /webapp directory. So under the src/main directory, create a new directory named webapp . If no view resolvers are configured, a handler method should return the actual view file name, for example:

@RequestMapping("/test") public String test()

To follow common convention and to protect JSP pages, create directories WEB-INF/jsp inside webapp . And create contact.jsp file under src/main/webapp/WEB-INF/jsp as shown in the following screenshot:

webapp directory structure

To configure Spring MVC view resolver, open the application.properties file and put the following properties:

spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
Now, let’s update code for the contact.jsp file as follows:
      Contact List - Spring Boot Web Application Example  

My Contact List


$ $ $
NameEmailCountry

As you can see, this JSP page uses JSTL’s forEach tag to iterate over Contact objects in the collection named contacts in the model, and generate HTML code to display the contact list.

Stop and re-run the SpringBootWebAppExampleApplication program. Click the hyperlink in the welcome page and the contact list appears, as shown in the following screenshot:

<a href=contact list page" />

Voila, it works as expected!


5. How to use ThymeLeaf with Spring Boot

To use ThymeLeaf as the view technology instead of JSP, add the following dependency in the pom.xml file:

 org.springframework.boot spring-boot-starter-thymeleaf 

Of course you should remove the dependencies tomcat-embed-jasper and jstl as we can’t use both JSP and ThymeLeaf.

By default, Spring Boot looks for ThymeLeaf template files under src/main/resources/templates directory. So create the contact.html file under this directory with the following code:

    Contact List - Spring Boot Web Application Example  

My Contact List


Name Email Country
Name Email Country
Run the program again and you will see the same result as using JSP.

6. How to use CSS, Javascript and Images

You can use these types of web files as normal, just make sure to put them under src/main/resources/templates if you use ThymeLeaf and under src/main/webapp/WEB-INF in case you use JSP.

7. Configure Logging

Spring Boot uses various logging libraries: Commons Logging for its core and Java Util Logging, Log4J2 and Logback for the dependencies which use different logging libraries. The default log format is pretty fine and the default log level is INFO.

If you want to change the log level for all libraries, specify the following entry in the application.properties file:

logging.level.root= The log level can be one of FATAL, ERROR, WARN, INFO, DEBUG, TRACE or OFF. For example:
logging.level.root=WARN
This changes the log level to WARN (show only warning and error messages) for all loggers.

For fine tuning, you can change log level for a specific Java package by specifying the following entry:

logging.level.= For example:
logging.level.net.codejava=ERROR
This changes log level for all classes in the net.codejava package to ERROR.

To enable debug mode for the application, specify debug=true in your application.properties file or specify the --debug flag as an argument when running the program, for example:

java -jar yourappname.jar --debug

Be patient when running the application in debug mode because it prints a huge amount of information, which slows down the application significantly.

8. Configure Server Port Number and Context Path

The default port number of embedded Tomcat server is 8080. You can override this default by specifying the server.port property in the application.properties file like this:

server.port=80

And the default context path is empty (‘’) so you can access the web application via http://localhost. To override this default, specifying the server.servlet.context-path in the application.properties file, for example:

server.servlet.context-path=/ContactApp
With two changes above, you now see the contact list via this URL:
http://localhost/ContactApp/list_contact

9. How to package Spring Boot web application to JAR/WAR

A major advantage of Spring Boot is that it packages your web application and embedded Tomcat server into a single executable JAR file, which is very convenient. However, JSP doesn’t work with JAR packaging (although it works in Eclipse!). So if you use JSP, you must change the packaging type to WAR in your pom.xml as follows:

And Thymeleaf works with either jar or war packaging type. With war packaging, Maven will generate an executable WAR file.

To package your Spring Boot web application to a JAR or WAR file in Eclipse, right-click on the project name, click Run As > Maven build… In the Edit Configuration dialog, type package as the goal and click Run:

maven package in eclipse

If using command line, change the current directory is your project directory, and simply type:

mvn package

Then check the target folder in your project directory, a JAR/WAR file is generated depending on the packaging type you use. And run the application:

java -jar SpringBootWebAppExample.jar

Note: Use the same command to run a WAR file because it is executable. You can also watch the following videos for more visual steps:

And for your reference, we have the final project structure which looks like this:

project structure

That’s how to develop a Spring MVC web application with Spring Boot in Eclipse IDE. Almost the configuration is done by Spring Boot so you can quickly start coding your business logic, following the sensible defaults. And keep in mind that you have to use war packaging with JSP.

References:

Other Spring Boot Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Attachments:
SpringBootWebAppExample.zip[Spring Boot Web Application Project Source Code]56 kB