1. 程式人生 > >Springboot 之 引入Thymeleaf

Springboot 之 引入Thymeleaf

Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎。

application.propertiesde 的檔案中配置Thymeleaf

#thymeleaf start
spring.thymeleaf.cache=false
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#thymeleaf end

Controller

package springboot;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @GetMapping(value = "/index")
    public String index(Model model) {
        logger.info("IndexController -> index");
        model.addAttribute("name", "Dear");
        return "index";
    }

}

index page

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'Hello!, ' + ${name} + '!'"></p>
</body>
</html>