HelloKoding

Practical coding guides

Spring Boot JSP Web MVC Example

This tutorial walks you through the steps of creating a MVC web app example with Spring Boot and JSP

The tech stack

  • MVC represents Model-View-Controller. It is a design pattern to separate an user-interface application into 3 main interconnected components for enabling loosely coupling development practices
  • Spring Boot is a popular Java-based framework used to build production-grade web applications and services
  • JSP stands for Jakarta Server Pages (aka JavaServer Pages). It is a server-side template engine helping create dynamic generated HTML web pages

What you’ll build

Spring Boot Hello World

What you’ll need

  • Your favorite IDE or Editor
  • JDK 8+ or OpenJDK 8+
  • Maven 3+

Init project structure

Beside using IDE, you can create and init a new Spring Boot project with Spring CLI or Spring Initializr. Learn more about using these tools here

The final project structure as below

├── 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

Project dependencies

Add spring-boot-starter-web and tomcat-embed-jasper into your project as a dependency on pom.xml or build.gradle file. The library versions can be omitted as it is resolved by the parent pom provided by Spring Boot

<dependencies>
    <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>
</dependencies>

The tomcat-embed-jasper provides the Eclipse Java Compiler for compiling jsp files into Java classes and provides the Jakarta Expression Language (EL) implementation for enabling HTML web pages to access data and functions in Java objects

You can find the full pom.xml file as below

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hellokoding.springboot</groupId>
    <artifactId>springboot-jsp-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

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

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

Create Controller

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";
    }
}

@Controller indicates the annotated class is a web controller which is used for defining web requests handlers to share data between Model and View

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

@RequestParam binds method parameter name to request query string parameter (value="name",...)

Model is an object 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 below application.properties file. So in this hello handler method, the return view is hello.jsp

View Template

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 value of this EL ${name} is filled by model.addAttribute(“name”, name); which is defined in HelloController

Static files

JSP is only for connecting HTML pages with Java objects. To implement custom style and handle user interface logic for your web site, you will always need CSS and JavaScript

Here we creates two simple files to see how they can be linked to the above JSP file

main.css

.hello-title{
    color: darkgreen;
}

main.js

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

Application Configurations

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);
    }
}

application.properties

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

Spring Boot uses spring.mvc.view.prefix and spring.mvc.view.suffix properties to auto-config InternalResourceViewResolver for mapping controller with JSP views

Run and Test

You can run the application by typing the following command on the terminal console at the project root directory

$ mvn 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!

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

mvn clean package
java -jar target/springboot-jsp-helloworld-1.0-SNAPSHOT.jar

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-jsp-helloworld

Follow HelloKoding