Review all the necessary steps required to create a simple web application with the Spring Framework 5.

Time: 25 minutes.

Requirements:

Simple Spring Web Application with Thymeleaf

  1. To create a simple Spring Web application, open a terminal window and execute the following statement:

    mvn archetype:generate -DgroupId=io.pivotal.workshop -DartifactId=simple-spring-webapp -Dversion=1.0-SNAPSHOT -DinteractiveMode=false -DarchetypeArtifactId=maven-archetype-webapp
    If you have a Maven version below 3.x, you need to use the command mvn archetype:create instead.
  2. Create the missing Java EE structure (ex: src/main/java, src/main/webapp/WEB-INF, etc.)

  3. Create the web controller SimpleController class in src/main/java/io/pivotal/workshop/web folder.

    io.pivotal.workshop.web.SimpleController.java
    package io.pivotal.workshop.web;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class SimpleController{
    
            Logger log = LoggerFactory.getLogger(SimpleController.class);
    
            @RequestMapping("/")
            public ModelAndView index(){
                    log.debug("About to redirect...");
                    return new ModelAndView("redirect:/showMessage");
            }
    
            @RequestMapping(value="/showMessage",method = RequestMethod.GET)
            public ModelAndView helloWorld(){
                    final String message = "Simple Spring MVC Web App with Thymeleaf and Spring 5";
                     log.debug("Showing the Message: " + message);
                    ModelAndView model = new ModelAndView("showMessage");
                    model.addObject("message", message);
                    return model;
            }
    }
  4. Modify the src/main/webapp/WEB-INF/web.xml file.

    web.xml
    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Simple Spring Web Application</display-name>
    
      <servlet>
          <servlet-name>dispatcherServlet</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
    
      <servlet-mapping>
          <servlet-name>dispatcherServlet</servlet-name>
          <url-pattern>/</url-pattern>
      </servlet-mapping>
    
    </web-app>
  5. Create the src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml file.

    dispatcherServlet-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
            <!--
            DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed
            by this context.
            -->
    
             <context:component-scan base-package="io.pivotal.workshop.web" />
    
            <!-- Useful when only JSP is required. The javax.servlet.jsp:avax.servlet.jsp-api:2.3.1 dendency is necessary-->
            <!--
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/view/"/>
                    <property name="suffix" value=".jsp"/>
            </bean>
            -->
    
            <!-- Thymeleaf Configuration -->
            <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <property name="prefix" value="/WEB-INF/view/" />
                    <property name="suffix" value=".html" />
                    <property name="templateMode" value="HTML5" />
            </bean>
    
            <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
                    <property name="templateResolver" ref="templateResolver" />
                    <property name="enableSpringELCompiler" value="true" />
            </bean>
    
            <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
                    <property name="templateEngine" ref="templateEngine" />
    </bean>
    
    </beans>
  6. Modify the src/main/webapp/index.html file and move it to the src/main/webapp/WEB-INF/view directory.

    index.html
    <!DOCTYPE html>
    
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
            <head>
                    <meta charset="utf-8">
                    <title>Welcome</title>
            </head>
            <body>
                    <p>This page never will show up</p>
            </body>
    </html>

    This page will never show up, because the handler will do a redirect to the showMessage.html.

  7. Create the src/main/webapp/WEB-INF/view/showMessage.html file.

    showMessage.jsp
    <!DOCTYPE html>
    
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
            <head>
                    <meta charset="utf-8">
                    <title>Welcome</title>
            </head>
            <body style="font-family: Verdana, sans-serif;">
            <h2><p th:text="${message}"/></h2>
            </body>
    </html>
  8. Create the logging configuration. Create a logback.xml file in the src/main/resources directory.

    logback.xml
    <configuration>
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            </encoder>
        </appender>
    
        <logger name="io.pivotal.workshop" level="DEBUG"/>
            <logger name="org.thymeleaf" level="OFF"/>
    
        <root level="INFO">
            <appender-ref ref="STDOUT" />
        </root>
    </configuration>
  9. Modify the pom.xml file. Add the necessary dependencies. See all the Spring 5 dependencies.

    pom.xml
    <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/maven-v4_0_0.xsd">
            <modelVersion>4.0.0</modelVersion>
            <groupId>io.pivotal.workshop</groupId>
            <artifactId>simple-spring-webapp</artifactId>
            <packaging>war</packaging>
            <version>1.0-SNAPSHOT</version>
            <name>simple-spring-webapp Maven Webapp</name>
            <url>http://maven.apache.org</url>
            <parent>
                    <groupId>io.pivotal.education.boot</groupId>
                    <artifactId>parentProject</artifactId>
                    <version>1.0.a.RELEASE</version>
                    <relativePath>../../</relativePath>
            </parent>
            <properties>
    
                    <!-- Generic properties -->
                    <java.version>1.8</java.version>
    
                    <!-- Web -->
                    <servlet.version>3.1.0</servlet.version>
    
                    <!-- Spring -->
                    <spring-framework.version>5.0.1.RELEASE</spring-framework.version>
    
                    <!-- Thymeleaf -->
                    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    
                    <!--  Logging -->
                    <slf4j.version>1.7.25</slf4j.version>
                    <logback.version>1.2.3</logback.version>
            </properties>
    
            <dependencies>
    
                    <!-- Spring MVC -->
                    <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-context</artifactId>
                            <version>${spring-framework.version}</version>
                    </dependency>
                    <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-aop</artifactId>
                            <version>${spring-framework.version}</version>
                    </dependency>
                    <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-webmvc</artifactId>
                            <version>${spring-framework.version}</version>
                    </dependency>
                    <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-web</artifactId>
                            <version>${spring-framework.version}</version>
                    </dependency>
    
                    <dependency>
                            <groupId>org.thymeleaf</groupId>
                            <artifactId>thymeleaf</artifactId>
                            <version>${thymeleaf.version}</version>
                    </dependency>
                    <dependency>
                            <groupId>org.thymeleaf</groupId>
                            <artifactId>thymeleaf-spring5</artifactId>
                            <version>${thymeleaf.version}</version>
                    </dependency>
    
    
                    <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-api</artifactId>
                            <version>${slf4j.version}</version>
                    </dependency>
                    <dependency>
                            <groupId>ch.qos.logback</groupId>
                            <artifactId>logback-classic</artifactId>
                            <version>${logback.version}</version>
                    </dependency>
    
                    <!-- Other Web dependencies -->
                    <dependency>
                            <groupId>javax.servlet</groupId>
                            <artifactId>javax.servlet-api</artifactId>
                            <version>${servlet.version}</version>
                            <scope>provided</scope>
                    </dependency>
            </dependencies>
    
            <build>
                    <finalName>simple-spring-webapp</finalName>
            </build>
    </project>

Building the Spring Web Application

To build the Spring Web application, execute the following command:

mvn clean compile package

the above command will generate the target/simple-spring-webapp.war.

Deploying the Spring Web Application

To deploy the application, install any application container that supports the Java Servlets specification.

For example, to deploy to Apache Tomcat, copy the target/simple-spring-webapp.war file into the $TOMCAT-INSTALLATION/webapps/ directory and start the container. Then, go to your browser and hit the http://localhost:8080/simple-spring-webapp/ URL.

You should see the text: Simple Spring MVC Web App with Thymeleaf and Spring 5.