Spring Boot JSP example

Posted by slamMan on Thu, 27 Jan 2022 03:10:18 +0100



Spring Boot JSP Tutorial with Example

This tutorial will guide you through the steps of creating a sample Hello World Web application using Spring Boot and JSP

JSP stands for Jakarta Server Pages (also known as JavaServer Pages). It is a server-side template engine that helps create dynamic HTML web pages

What will you build

What do you need?

  • JDK 8 + or OpenJDK 8+

  • Expert 3+

  • Your favorite IDE

Project structure

The following is the final project structure of all the files we will 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
copy

pom.xml is a configuration file used by Maven to manage project dependencies and build processes. It is usually placed in the project root directory

The Web controller class is used to map user requests to JSP files and will be created in src/main/java

The JSP view template file will be created in src/main/webapp/WEB-INF/jsp

CSS and JavaScript files will be created in src/main/resources/static

application.properties is the configuration file used by Spring Boot and will be created in src/main/resources

Application.java is the startup file of the Spring Boot startup application, which will be created in src/main/java

Initialize a new Spring Boot application

In addition to using IDE, we can also use Spring Initializr to create and initialize new Spring Boot projects through Web UI or command-line tools (such as cURL, HTTPie or Spring Boot CLI). Here Learn more about using these tools

First, we will select Web and Devtools as dependencies. The following is an example of 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
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 HK springboot JSP Zip file and import the sample project into your IDE

Project dependency

For the Spring Boot JSP Web application, we need POM The following dependencies of the XML file

  • Spring Boot starter Web provides all the dependencies and automatic configuration we need to develop Web applications in Spring Boot, including Tomcat embedded servlet container

  • Tomcat embedded Jasper provides support for compiling JSP files in Tomcat

The library version can be omitted because it will be solved 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>
copy

In addition, whenever the static file on the Java class or classpath changes, we also use the spring boot devtools dependency to automatically trigger the application restart or real-time reload in the development environment. However, to take advantage of it, you need to configure the IDE to automatically save and compile files when they are modified

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

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

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

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

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

@RequestParam binds the method parameter name to the request query string parameter

Model is a Spring object used to share data between handlers and view templates

The name of the view template is determined by the statement of the return handler and the file spring mvc. view. The configuration attribute defined in suffix defines application properties. So in this Hello processing method, the returned view is hello jsp

JSP view template file

Create a simple JSP view template file to display dynamic messages to users

[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>
copy

The dynamic message is ${name}. It's a Java expression language To enable JSP files to access data in the model. Its value is determined by model addAttribute("name", name); Population defined in HelloController above

Static file

Create two simple CSS and JavaScript files in / src/main/resources/static

The main CSS files are linked to JSP views in the following ways < link href = "/ CSS / main.css" rel = "stylesheet" >

[main.css]

.hello-title{
    color: darkgreen;
}
copy

The main JS files are included in the JSP view in the following ways < script SRC = "/ JS / main.js" > < / script >

[main.js]

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

Application configuration

Create an application. In-house Properties file src/main/resources mvc. The view property configures the Spring MVC view parser

[application.properties]

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

The spring mvc. view. The prefix attribute defines the path of the JSP file, which is spring mvc. view. The suffix attribute defines the file extension we want to use

org. springframework. boot. autoconfigure. web. The servlet is in the background. Spring Boot will automatically configure the Spring MVC view parser by using the following methods of webmvcoautoconfiguration in the package according to the above settings

[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;
}
copy

Operation and testing

Create an Application class and start the Application with the @ SpringBootApplication annotation

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

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

./mvnw clean spring-boot:run
copy

You will see this text in the console

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

Access on your web browser http://localhost:8080 , the following responses are expected

Hello, World!
copy

Try to modify JSP, CSS and JavaScript files and refresh the browser. The HTML response will be updated accordingly. Thank you from spring boot devtools

In a production environment, you might want to package the Spring Boot application and run it as a single jar file

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

conclusion

In this tutorial, we learned to use JSP to create a Hello World Web Application in Spring Boot. Source code in Available on Github

 

Topics: Java Spring Boot