[JAVA] Spring5 MVC Web App Development with Visual Studio Code Hello World Creation

Introduction

Hello World will be created in the template created in here.

environment

OS:Windows 10 Pro 64bit Editor:Visual Studio Code 1.42.1 JDK:AdoptOpenJDK 11.0.6+10 x64 Apache Maven:v3.6.3 Apache Tomcat:v9.0.31

pom.xml Add the Repository required for Spring MVC to pom.xml.

MVN REPOSITORY is used to search the Repository. https://mvnrepository.com/

Add to properties

<spring.version>5.2.4.RELEASE</spring.version>
<!-- web.Run the build even if you don't have xml-->
<failOnMissingWebXml>false</failOnMissingWebXml>

Add to dependencies

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
	<scope>compile</scope>
</dependency>

<dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context-support</artifactId>
    	<version>${spring.version}</version>
    	<scope>compile</scope>
</dependency>

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
	<version>3.0.11.RELEASE</version>
	<scope>compile</scope>
</dependency>

<dependency>
  	<groupId>org.thymeleaf.extras</groupId>
    	<artifactId>thymeleaf-extras-springsecurity5</artifactId>
    	<version>3.0.4.RELEASE</version>
    	<scope>compile</scope>
</dependency>

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>4.0.1</version>
	<scope>provided</scope>
</dependency>

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.10</version>
	<scope>provided</scope>
</dependency>

The entire pom.xml.

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.example</groupId>
	<artifactId>hello</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>11</java.version>
		<spring.version>5.2.4.RELEASE</spring.version>
        <!-- web.Run the build even if you don't have xml-->
        <failOnMissingWebXml>false</failOnMissingWebXml>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
    		<groupId>org.springframework</groupId>
    		<artifactId>spring-context-support</artifactId>
    		<version>${spring.version}</version>
    		<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring5</artifactId>
			<version>3.0.11.RELEASE</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
			<version>3.0.4.RELEASE</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.10</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>

MvcConfig.java Create it in "D: \ JAVA \ Project \ hello \ src \ main \ java \ com \ example \ web \ config". If the folder does not exist, create it.

MvcConfig.java


package com.example.web.config;

import java.nio.charset.StandardCharsets;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.VersionResourceResolver;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

@EnableWebMvc //Enable Spring MVC
@Configuration
@ComponentScan(basePackages = {"com.example.web.controller"})
public class MvcConfig implements WebMvcConfigurer {
	@Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver =
                new SpringResourceTemplateResolver();
        //Specify the name of the folder where you want to save the view
        templateResolver.setPrefix("/WEB-INF/templates/");
        //Specify the view extension
        templateResolver.setSuffix(".html");
        //Specify template mode in HTML
        templateResolver.setTemplateMode(TemplateMode.HTML);
        //Specify the character code when loading the template
        templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());

        templateResolver.setCacheable(false);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        //Set SpringResourceTemplateResolver
        templateEngine.setTemplateResolver(templateResolver());
        //Enable SpEL's compiler to improve performance
        templateEngine.setEnableSpringELCompiler(true);
        //Added Dialect to use Date and Time APi
        templateEngine.addDialect(new Java8TimeDialect());
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        //Specify the character code when exporting the view
        viewResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
        registry.addResourceHandler("/webjars/**")
        		.addResourceLocations("classpath:/META-INF/resources/webjars/")
        		.resourceChain(false)
        		.addResolver(new VersionResourceResolver()
        				.addContentVersionStrategy("/**"));
    }

    //Message source settings
    //Property files can be used on web pages
    //Japanese messages: messages_ja.properties
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");

        //If set to true, the key will be displayed if the message key does not exist.
        //If false, throw NoSuchMessageException
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        // # -1 :Do not reload, 0:Always reload
        messageSource.setCacheSeconds(0);
        return messageSource;
    }
}

WebAppInitializer.java Create it in "D: \ JAVA \ Project \ hello \ src \ main \ java \ com \ example \ web \ config". If the folder does not exist, create it.

WebAppInitializer.java


package com.example.web.config;

import java.nio.charset.StandardCharsets;

import javax.servlet.Filter;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	/**
     *Specifies Java Config classes for non-Spring MVC, such as business logic.
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] {};
    }

    /**
     *Specifies the Java Config class for Spring MVC.
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] {MvcConfig.class};
    }

    /**
     *Specifies the URL pattern for the DispatcherServlet.
     * "/"By specifying, DispatcherServlet receives all requests.
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     *Specify the Servlet filter.
     *If there are multiple filters, they will be executed in the order specified in the array.
     */
    @Override
    protected Filter[] getServletFilters() {
        return new Filter[]{
                new CharacterEncodingFilter(StandardCharsets.UTF_8.name(), true)};
    }
}

Creating a Controller

Create it in "D: \ JAVA \ Project \ hello \ src \ main \ java \ com \ example \ web \ controller". If the folder does not exist, create it.

RootController.java


package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RootController {

    @GetMapping("/")
    public String root() {
        // "redirect:"Prefix to redirect
        return "redirect:hello/index";
    }

}

HelloController.java


package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/index")
    public String indexGet() {
        return "hello/index";
    }
}

Create View

Create it in "D: \ JAVA \ Project \ hello \ src \ main \ webapp \ WEB-INF \ templates \ hello". If the folder does not exist, create it.

index.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Hello World</title>
    </head>
    
    <body>
        <h1>Hello World</h1>
    </body>
</html>

compile

You can compile and create a war file with the following command.

mvn package
D:\JAVA\Project\hello>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.example:hello >--------------------------
[INFO] Building hello 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\JAVA\Project\hello\src\main\resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 4 source files to D:\JAVA\Project\hello\target\classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\JAVA\Project\hello\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hello ---
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ hello ---
[INFO] Packaging webapp
[INFO] Assembling webapp [hello] in [D:\JAVA\Project\hello\target\hello-1.0-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [D:\JAVA\Project\hello\src\main\webapp]
[INFO] Webapp assembled in [164 msecs]
[INFO] Building war: D:\JAVA\Project\hello\target\hello-1.0-SNAPSHOT.war
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.883 s
[INFO] Finished at: 2020-03-08T20:35:04+09:00
[INFO] ------------------------------------------------------------------------

Operation check

Command palette

Tomcat: Add Tomcat Server

The Tomcat folder selection dialog will be displayed. Select the folder where you unzipped Tomcat (D: \ JAVA \ Tomcat \ apache-tomcat-9.0.31).

Command palette

Tomcat: Run on Tomcat Server

A war file selection dialog will be displayed. Select the war file (D: \ JAVA \ Project \ SpringSample01 \ target \ hello-1.0-SNAPSHOT.war) created by "mvn package".

Please access "[http: // localhost: 8080 /](http: // localhost: 8080 /)". Depending on the settings, the browser will start automatically. tomcat2.jpg

Click hello-1.0-SNAPSHOT.

"Hello World" is displayed. tomcat3.jpg

This sample source

Uploaded to GitHub. https://github.com/t-skri1/SpringSample01

Reference / Source

Web application development memo with MVN, Tomcat, JSP / Servlet with VScode https://qiita.com/harhogefoo/items/2fa52ecee90b7a25e4c9

Summary

This sample is only View and Controller in MVC. Separate settings are required to add a Model. I will post the setting method in the sample connection to SQL Server.

Recommended Posts

Spring5 MVC Web App Development with Visual Studio Code Hello World Creation
Spring Boot2 Web application development with Visual Studio Code Hello World creation
Spring5 MVC Web application development with Visual Studio Code Maven template creation
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 2/3 [Page creation 1/2]
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 3/3 [Page creation 2/2]
Spring5 MVC Web application development with Visual Studio Code Spring Security usage 1/3 [Preparation]
Spring5 MVC web application development with Visual Studio Code SQL Server connection
Spring Boot2 Web application development with Visual Studio Code SQL Server connection
Spring5 MVC Web application development with Visual Studio Code Environment construction (Installation of JDK11, Maven, Tomcat, Visual Studio Code)
Create a Hello World web app with Spring framework + Jetty
Build WebAPP development environment with Java + Spring with Visual Studio Code
Build Java program development environment with Visual Studio Code
Hello World (console app) with Apache Camel + Spring Boot 2
Hello World with Spring Boot
Hello World with Spring Boot!
Hello World with VS Code!
Hello World with Spring Boot
Use PlantUML with Visual Studio Code
Until "Hello World" with Spring Boot
(Intellij) Hello World with Spring Boot
Hello World with Eclipse + Spring Boot + Maven
Start web application development with Spring Boot
Java development with Codenvy: Hello World! Run
How Spring Security works with Hello World
(IntelliJ + gradle) Hello World with Spring Boot
A record of setting up a Java development environment with Visual Studio Code
Experience .NET 5 with Docker and Visual Studio Code
Hello world! With Spring Boot (Marven + text editor)
Hello World at explosive speed with Spring Initializr! !! !!
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
Try to display hello world with spring + gradle
Getting started with Java programs using Visual Studio Code
Hello World (REST API) with Apache Camel + Spring Boot 2
Why can I develop Java with Visual Studio Code?
Hello World with Micronaut
Java web application development environment construction with VS Code (struts2)
To receive an empty request with Spring Web MVC @RequestBody
Java Config with Spring MVC
[Spring Boot] Web application creation
Java in Visual Studio Code
Hello World with SpringBoot / Gradle
Hello, World! With Asakusa Framework!
How to use PlantUML with Visual Studio Code (created on October 30, 2020)
Until you run Hello World of JavaFX with VS Code + Gradle
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
[With sample code] Basics of Spring JDBC to learn with Blog app
What I learned from doing Java work with Visual Studio Code
Minecraft Mod development environment construction (IntelliJ IDEA + Minecraft Forge 1.15.2) + Hello World Mod creation
[For beginners] Introducing the procedure to Hello, World in C/C ++ language using Visual Studio Code on Ubuntu