建立一個基於Thymeleaf
的範例專案,以演示Spring CLI的功能。 按照下面提到的步驟建立一個範例專案 -
在D:/worksp/springboot-cli/
目錄下,建立一個名稱為TestApplication
的檔案夾,並在這個檔案中建立兩個子目錄:static
和templates
。
在TestApplication
檔案夾中建立message.groovy
檔案,在templates
檔案夾中建立message.html
,在static
檔案夾中建立index.html
,如下所述。
編譯並執行應用程式以驗證實現的邏輯的結果。
檔案:TestApplication/message.groovy -
@Controller
@Grab('spring-boot-starter-thymeleaf')
class MessageController {
@RequestMapping("/message")
String getMessage(Model model) {
String message = "Welcome to Tw511.Com!";
model.addAttribute("message", message);
return "message";
}
}
檔案:TestApplication/templates/message.html -
<!DOCTYPE HTML>
<html xmlns:th = "http://www.thymeleaf.org">
<head>
<title>Spring Boot CLI Example</title>
<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
</head>
<body>
<p th:text = "'Message: ' + ${message}" />
</body>
</html>
檔案: TestApplication/static/index.html -
<!DOCTYPE HTML>
<html>
<head>
<title>Spring Boot CLI Example</title>
<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
</head>
<body>
<p>Go to <a href = "/msg">Message</a></p>
</body>
</html>
輸入以下命令 -
D:/worksp/springboot-cli/TestApplication/> spring run *.groovy
現在,Spring Boot CLI將開始執行,下載所需的依賴項,執行嵌入式tomcat,部署應用程式並啟動它。可以在控制台上看到以下輸出 -
Resolving dependencies.............................
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _> | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
...
2018-11-08 16:27:28.300 INFO 8360 --- [ runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-11-08 16:27:28.305 INFO 8360 --- [ runner-0] o.s.boot.SpringApplication
基於Spring應用現已準備就緒,開啟網址為「http://localhost:8080/」
,將看到以下輸出 -
Go to Message
單擊訊息連結,將看到以下輸出 -
Message: Welcome to Tw511.Com!
以下操作由Spring CLI執行 -
war
,在預設埠8080上啟動嵌入式tomcat伺服器。