渲染模板 thymeleaf 的使用
阿新 • • 發佈:2020-09-15
首先匯入thymeleaf:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
使用:
只要把HTML頁面放在classpath:/templates/下, thymeleaf就能自動渲染
例如, 在resources目錄下:
resources目錄下建立hello.html
templates目錄下建立success.html
controller程式碼如下:
package com.ryan.springdemothymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controllerpublic class Hellocontroller { @ResponseBody @RequestMapping("/Hello") public String hello(){ return "Hello World!"; } @RequestMapping("/success") public String success(){ return "success.html"; } }
在瀏覽器訪問 localhost:8080/hello.html 可訪問hello.html檔案
在瀏覽器訪問 localhost:8080/success 可訪問success.html檔案 (不新增.html)