Spring Boot Hello World(Thymeleaf)示例
這是一個Spring Boot Web應用示例,使用嵌入式Tomcat + Thymeleaf模板引擎,並將其作爲可執行JAR文件。
使用的相關技術:
- Spring Boot 1.4.2.RELEASE
- Spring 4.3.4.RELEASE
- Thymeleaf 2.1.5.RELEASE
- Tomcat Embed 8.5.6
- Maven 3
- Java 8
1. 項目目錄
手動創建以下文件夾目錄結構:
2. 項目依賴
聲明 spring-boot-starter-thymeleaf
以獲得開發Spring + Thymeleaf Web應用程序所需的任何程序類庫。
參考如下 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>
<artifactId>spring-boot-web-thymeleaf</artifactId>
<packaging>jar</packaging>
<name>Spring Boot Web Thymeleaf 示例</name>
<description>Spring Boot Web Thymeleaf 示例描述</description>
<url>http://www.yiibai.com</url>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- hot swapping, disable cache for template, enable live reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Optional, for bootstrap -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
顯示項目依賴關係:
提示: spring-boot-devtools
這個spring-boot-devtools有助於禁用緩存並啓用熱插拔,以便開發人員總是看到最後的更改。 有利於發展。 閱讀這篇 - Spring Boot - 開發工具。嘗試修改Thymeleaf模板或屬性文件,刷新瀏覽器以查看更改立即生效。
3. Spring Boot
使用[@SpringBootApplication](https://github.com/SpringBootApplication "@SpringBootApplication")
進行註釋。 運行此類來啓動Spring Boot Web應用程序。
SpringBootWebApplication.java
package com.yiibai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
一個簡單的Spring控制器類: WelcomeController.java 代碼如下 -
package com.yiibai;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WelcomeController {
// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";
@RequestMapping("/")
public String welcome(Map<String, Object> model) {
model.put("message", this.message);
return "welcome";
}
}
4. Thymeleaf +資源+靜態文件
對於Thymeleaf
模板文件,放入 src/main/resources/templates/
目錄下, src/main/resources/templates/welcome.html
文件代碼如下 -
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Hello World示例</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" th:href="@{/css/main.css}"
href="../../css/main.css" />
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Spring Boot</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">首頁</a></li>
<li><a href="#about">關於</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1>Spring Boot Web Thymeleaf示例</h1>
<h2>
<span th:text="'Message: ' + ${message}"></span>
</h2>
</div>
</div>
<!-- /.container -->
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
`
對於靜態文件,如CSS或Javascript,將它們放入 /src/main/resources/static/
目錄, /src/main/resources/static/css/main.css
文件代碼如下 -
h1{
font-size: 20pt;
}
h2{
font-size: 16pt;
}
對於屬性文件,放入 /src/main/resources/
目錄中, /src/main/resources/application.properties
文件中的代碼內容如下 -
welcome.message: Hello, Spring Boot
注意: 閱讀此Spring Boot服務靜態內容以瞭解資源映射。
5. 運行演示
啓動Spring Boot Web應用程序,使用Maven命令:mvn spring-boot:run
,運行結果輸出結果如下 -
F:\worksp\springboot\spring-boot-web-thymeleaf > mvn spring-boot:run
... ....
Downloaded: http://repo.maven.apache.org/maven2/commons-io/commons-io/1.3.2/commons-io-1.3.2.jar (86 KB at 1.4 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/apache/commons/commons-compress/1.9/commons-compress-1.9.jar (370 KB at 5.9 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/jdom/jdom/1.1/jdom-1.1.jar (150 KB at 2.3 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/sonatype/sisu/sisu-guice/2.1.7/sisu-guice-2.1.7-noaop.jar (461 KB at 6.8 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/com/google/guava/guava/18.0/guava-18.0.jar (2204 KB at 15.6 KB/sec)
[INFO] Attaching agents: []
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
::Spring Boot:: (v1.4.2.RELEASE)
2017-03-22 02:45:51.162 INFO 5284 --- [ restartedMain] com.yiibai.SpringBootWebApplication : Starting SpringBootWebApplication on MY-PC with PID 5284 (F:\worksp\springboot\web-thymeleaf\target\classes started by Administrator in F:\worksp\springboot\web-thymeleaf)
2017-03-22 02:45:51.162 INFO 5284 --- [ restartedMain] com.yiibai.SpringBootWebApplication : No active profile set, falling back to default profiles: default
2017-03-22 02:45:51.740 INFO 5284 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@e33d3c1: startup date [Wed Mar 22 02:45:51 CST 2017]; root of context hierarchy
2017-03-22 02:45:57.190 INFO 5284 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-03-22 02:45:57.221 INFO 5284 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-03-22 02:45:57.221 INFO 5284 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.6
2017-03-22 02:45:57.471 INFO 5284 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-03-22 02:45:57.471 INFO 5284 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5731 ms
2017-03-22 02:45:57.815 INFO 5284 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-03-22 02:45:57.830 INFO 5284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-03-22 02:45:57.846 INFO 5284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-03-22 02:45:57.846 INFO 5284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-03-22 02:45:57.846 INFO 5284 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-03-22 02:45:58.867 INFO 5284 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@e33d3c1: startup date [Wed Mar 22 02:45:51 CST 2017]; root of context hierarchy
2017-03-22 02:45:59.115 INFO 5284 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.yiibai.WelcomeController.welcome(java.util.Map<java.lang.String, java.lang.Object>)
2017-03-22 02:45:59.115 INFO 5284 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-03-22 02:45:59.115 INFO 5284 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-03-22 02:45:59.193 INFO 5284 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-22 02:45:59.193 INFO 5284 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-22 02:45:59.286 INFO 5284 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-22 02:46:10.440 INFO 5284 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-03-22 02:46:10.721 INFO 5284 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-03-22 02:46:14.581 INFO 5284 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-03-22 02:46:14.597 INFO 5284 --- [ restartedMain] com.yiibai.SpringBootWebApplication : Started SpringBootWebApp
運行成功後,打瀏覽器訪問: http://localhost:8080 ,沒有問題應該會看到以下輸出頁面 -
6. 構建可執行JAR
打包項目以創建可執行的JAR文件。使用Maven命令:mvn clean package
,
F:\worksp\springboot\spring-boot-web-thymeleaf> java -jar target/spring-boot-web-thymeleaf-1.0.jar
運行成功後,打瀏覽器再次訪問: http://localhost:8080 ,沒有問題應該會看到以下輸出頁面 -