SpringCloudSpringBootmybatis分散式微服務雲架構(八)開發Web應用(2)

it芒果發表於2018-08-07

在完成配置之後,舉一個簡單的例子,在快速入門工程的基礎上,舉一個簡單的示例來通過Thymeleaf渲染一個頁面。

@Controller
public class HelloController {
 
    @RequestMapping("/")
    public String index(ModelMap map) {
        // 加入一個屬性,用來在模板中讀取
        map.addAttribute("host", "http://blog.didispace.com");
        // return模板檔案的名稱,對應src/main/resources/templates/index.html
        return "index";  
    }
 
}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

如上頁面,直接開啟html頁面展現Hello World,但是啟動程式後,訪問http://localhost:8080/,則是展示Controller中host的值:http://blog.didispace.com,做到了不破壞HTML自身內容的資料邏輯分離。

更多Thymeleaf的頁面語法,還請訪問Thymeleaf的官方文件查詢使用。

Thymeleaf的預設引數配置

如有需要修改預設配置的時候,只需複製下面要修改的屬性到application.properties中,並修改成需要的值,如修改模板檔案的副檔名,修改預設的模板路徑等。

# Enable template caching.
spring.thymeleaf.cache=true 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# Content-Type value.
spring.thymeleaf.content-type=text/html 
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true 
# Template encoding.
spring.thymeleaf.encoding=UTF-8 
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names= 
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5 
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/ 
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

支援JSP的配置
Spring Boot並不建議使用,但如果一定要使用,可以參考此工程作為腳手架:JSP支援


相關文章