Creating your First Spring Boot – Web MVC Application

In this tutorial, we are going to see how to create a simple Spring Boot Web MVC Application. We are going to use the following tools and technologies:

  • Spring Boot – 2.1.3.RELEASE
  • Java 8
  • Maven
  • Eclipse STS

We will use JSP as a view for our application.

Package Structure

The project structure for the Spring MVC Web application is shown below:

Project Structure

Refer the following link to create a simple spring boot application using Maven: Creating Simple Spring Boot application

Once the simple spring boot application is setup, this acts as a skeleton to create our first Spring Boot Web MVC application as shown in the next sections.

Project Dependencies

In order to add Spring web MVC support in our application, add the following dependency in pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Here is a complete pom.xml for your reference:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>demo</name>
  <description>Demo project for Spring Boot</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Tomcat for JSP rendering -->
    <dependency> 
      <groupId>org.apache.tomcat.embed</groupId> 
      <artifactId>tomcat-embed-jasper</artifactId> 
    </dependency>
    
    <!-- JSTL tag lib -->
    <dependency>
     		<groupId>jstl</groupId>
    	    <artifactId>jstl</artifactId>
     		<version>1.2</version>
     		<scope>provided</scope>
 		</dependency>
    
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Main Application class

The main class is used to bootstrap a Spring Boot MVC Web application. Here is a simple application class that is used for this sample project:

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleApp{
  public static void main(String[] args) {
    SpringApplication.run(SampleApp.class, args);
  }
}

Controller Class

The Controller class is used to handle the web requests. Here is a sample controller for the purpose of this project.

There are 4 events that are involved when a request is sent to an application:

  • After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
  • The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
  • The DispatcherServlet will take help from ViewResolver to pick-up the defined view (JSP page) for the request.
  • Once view is finalized, The DispatcherServlet passes the model data to the view(JSP page) which is finally rendered by the browser.

For instance, Refer the code in the controller used in the project:

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWebController {
  @RequestMapping("/")
  public String hello() {
    return "login";
  }
  /*
   * Accepts the request param named 'name" and passes it to the next view i.e.,
   * welcome.jsp
   */
  @PostMapping("/welcome")
  public String welcome(@RequestParam("name") String name, Model model) {
    model.addAttribute("name", name); // Setting the model data in the view
    return "welcome"; // Returns the view name to be rendered by the browser, i.e., welcome.jsp
  }
}

Static Resources

All the static content like CSS, JS and images related to the application are stored under /static folder in the classpath resources (usually the classpath location is: src/main/resources)

In this example, we will put all JavaScript files under /static/js folder.

All CSS(Style sheets) are placed under /static/css folder.

//JS function to validate whether user entered the Name or not
function validate() {
  var name = document.getElementById("name").value;
  if (name == '') {
    alert('Please enter a valid name.');
    return false;
  } else {
    return true;
  }
}

Here is the CSS file used in this project:

/*Style for User Form*/
.form {
  background-color: #2adef6;
  width: 400px;
  height: 100px;
  border-radius: 15px;
  padding: 20px;
}
/*Style for Table column*/
td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

application.properties

Create an application.properties file under src/main/resources folder and add the following properties in it:

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
# Path pattern used for static resources.
spring.mvc.static-path-pattern=/resources/**  

Note – spring.mvc.static-path-pattern=/resources/** will map the classpath:/static/css/style.css to /resources/css/style.css. Similarly, the classpath:/static/js/int.js  will be mapped to /resources/js/app.js.

You can use these static resources in jsp as follows.

<link rel="stylesheet" href="/resources/css/style.css">
<script type="text/javascript" src="/resources/js/app.js"></script>

JSP Views

Create login.jsp and welcome.jsp  files under src/main/webapp/WEB-INF/jsp folder as shown in the project structure.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- Static content -->
<link rel="stylesheet" href="/resources/css/style.css">
<script type="text/javascript" src="/resources/js/int.js"></script>
<title>Spring Boot Web MVC Application</title>
</head>
<body>
  <h1>A sample Spring Boot - MVC web application</h1>
  <hr>
  <div class="form">
    <form action="welcome" method="post" onsubmit="return validate()">
      <table>
        <tr>
          <td>Please specify Your name</td>
          <td><input id="name" name="name"></td>
    </tr>
        <tr>
        <td></td>
        <td><input type="submit" value="Submit"></td>
        <td></td>
        </tr>
      </table>
    </form>
  </div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Boot</title>
</head>
<body>
  <h1>Spring Boot - MVC web application example</h1>
  <hr>
  <h2>Welcome back, ${name}</h2>
</body>
</html>

Running the Application

Run the SampleApp.java class as Java application i.e. go to Run→ Run as → Java Application

You should see the output as follows:

Now, enter the following URL in the browser: https://localhost:8080/

Now, enter your name and click on Submit, you will be shown the following welcome page

Conclusion

In this tutorial, we have seen how to create a simple Spring Boot MVC Web application using Maven build tool and JSP as view.

References

https://spring.io/guides/gs/serving-web-content/

Translate »