Spring Boot CLI Thymeleaf入門專案


建立一個基於Thymeleaf的範例專案,以演示Spring CLI的功能。 按照下面提到的步驟建立一個範例專案 -

第1步

D:/worksp/springboot-cli/目錄下,建立一個名稱為TestApplication的檔案夾,並在這個檔案中建立兩個子目錄:statictemplates

第2步

TestApplication檔案夾中建立message.groovy檔案,在templates檔案夾中建立message.html,在static檔案夾中建立index.html,如下所述。

第3步

編譯並執行應用程式以驗證實現的邏輯的結果。

檔案: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執行 -

  • 所有依賴項JAR僅在第一次使用時下載。
  • Spring CLI根據程式碼中使用的類和注釋自動檢測要下載的依賴項JAR。
  • 最後,它編譯程式碼,在嵌入式tomcat上部署war,在預設埠8080上啟動嵌入式tomcat伺服器。