This tutorial walks you through the steps of creating a Hello World web application example with Spring Boot and JSP

JSP stands for Jakarta Server Pages (aka JavaServer Pages). It is a server-side template engine helping create dynamic HTML web pages

What you'll build

What you'll need

  • JDK 8+ or OpenJDK 8+

  • Maven 3+

  • Your favorite IDE

Project structure

Following is the final project structure with all the files we would create

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── springboot
│       │               └── view
│       │                   ├── Application.java
│       │                   └── HelloController.java
│       ├── resources
│       │   ├── static
│       │   │   ├── css
│       │   │   │   └── main.css
│       │   │   └── js
│       │   │       └── main.js
│       │   └── application.properties
│       └── webapp
│           └── WEB-INF
│               └── jsp
│                   └── hello.jsp
└── pom.xml

pom.xml is the configuration file used by Maven to manage project dependencies and build process, it is usually placed in the project root directory

Web controller classes are used for mapping user requests to JSP files, would be created inside src/main/java

JSP view template files would be created inside src/main/webapp/WEB-INF/jsp

CSS and JavaScript files would be created inside src/main/resources/static

application.properties is a configuration file used by Spring Boot, would be created inside src/main/resources

Application.java is a launch file for Spring Boot to start the application, would be created inside src/main/java

Initialize a new Spring Boot application

Besides using IDE, we can create and init a new Spring Boot project by using Spring Initializr via web UI or command-line tools such as cURL, HTTPie, or Spring Boot CLI. Learn more about using these tools here

For getting started, we will choose Web and Devtools as dependencies. Below is an example with cURL

curl https://start.spring.io/starter.zip \  
    -d dependencies=web,devtools \
    -d javaVersion=1.8 \
    -d packageName=com.hellokoding.springboot \
    -d groupId=com.hellokoding.springboot \
    -d artifactId=hk-springboot-jsp \
    -o hk-springboot-jsp.zip

Unzip the hk-springboot-jsp.zip file and import the sample project into your IDE

Project dependencies

For a Spring Boot JSP web application, we will need the following dependencies on the pom.xml file

  • spring-boot-starter-web provides all the dependencies and auto-configuration we need to develop a web application in Spring Boot, including the Tomcat embedded servlet container

  • tomcat-embed-jasper provides the support for compiling JSP files in Tomcat

The library versions can be omitted as it will be resolved by the parent pom provided by Spring Boot

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>  
<dependency>  
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

Apart from that, we also use the spring-boot-devtools dependency to auto-trigger an application restart or live reload in the development environment whenever Java class or static files on class-path change, respectively. However, to leverage that, you need to configure your IDE to auto-save and auto-compile when files are modified

In the production environment, when a Spring Boot application is launched from a jar file, the devtools is auto disabled

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

Create Controller

Create a Spring Boot controller file to map HTTP requests to JSP view files

[HelloController.java]

package com.hellokoding.springboot.view;

import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {  
    @GetMapping({"/", "/hello"})
    public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
        model.addAttribute("name", name);
        return "hello";
    }
}

The @Controller annotation indicates the annotated class is a web controller

@GetMapping maps HTTP GET request for "/" (home page) and "/hello" to the hello method

@RequestParam binds method parameter name to request query string parameter

Model is a Spring object for sharing data between handler and view template

The view template name is defined by the return statement of the handler and the spring.mvc.view.suffix config property which defined in the application.properties file. So in this hello handler method, the return view is hello.jsp

JSP View Template files

Create a simple JSP view template file to show a dynamic message to user

[hello.jsp]

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">
    <title>Hello ${name}!</title>
    <link href="/css/main.css" rel="stylesheet">
</head>  
<body>  
    <h2 class="hello-title">Hello ${name}!</h2>
    <script src="/js/main.js"></script>
</body>  
</html>

The dynamic message is ${name}. It is an Java Expression Language enabling JSP files to access the data from the model. Its value is filled by the model.addAttribute("name", name); defined in the above HelloController

Static files

Create 2 simple CSS and JavaScript files inside /src/main/resources/static

The main.css file is linked into JSP view via <link href="/css/main.css" rel="stylesheet">

[main.css]

.hello-title{
    color: darkgreen;
}

The main.js file is included into JSP view via <script src="/js/main.js"></script>

[main.js]

(function(){
    console.log("Hello World!");
})();

Application Configurations

Create application.properties file inside src/main/resources to configure Spring MVC view resolver via the spring.mvc.view properties

[application.properties]

spring.mvc.view.prefix: /WEB-INF/jsp/  
spring.mvc.view.suffix: .jsp

The spring.mvc.view.prefix property defines the path to JSP files, the spring.mvc.view.suffix property defines the file extension we would like to use

Under the hood, Spring Boot will auto-configure Spring MVC view resolver based on the above settings by using the following methods of WebMvcAutoConfiguration inside org.springframework.boot.autoconfigure.web.servlet package

[WebMvcAutoConfiguration.java]

@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {  
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix(this.mvcProperties.getView().getPrefix());
    resolver.setSuffix(this.mvcProperties.getView().getSuffix());
    return resolver;
}

Run and Test

Create an Application class and use @SpringBootApplication annotation to launch the application

[Application.java]

package com.hellokoding.springboot.view;

import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {  
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Run the application by typing the following command on the terminal console at the project root directory

./mvnw clean spring-boot:run

You would see this text in the console

o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

Access to http://localhost:8080 on your web browser, the following response is expected

Hello, World!

Try to modify the JSP, CSS, and JavaScript files, and refresh the browser, the HTML response would be updated accordingly thanks to the support from spring-boot-devtools

In a production environment, you may like to package and run the Spring Boot application as a single jar file

./mvnw clean package
java -jar target/hk-springboot-jsp-0.0.1-SNAPSHOT.jar

Conclusion

In this tutorial, we learned to create a Hello World web application in Spring Boot with JSP. The source code is available on Github

You may also like Spring Boot Tutorials in Practice