Hello World will be created in the template created in here.
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)};
}
}
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 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>
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] ------------------------------------------------------------------------
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.
Click hello-1.0-SNAPSHOT.
"Hello World" is displayed.
Uploaded to GitHub. https://github.com/t-skri1/SpringSample01
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode https://qiita.com/harhogefoo/items/2fa52ecee90b7a25e4c9
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