zoukankan      html  css  js  c++  java
  • Thymeleaf 模板 在spring boot 中的引用和应用

    Thymeleaf是一个java类库,他是一个xml/xhtml/html5的模板引擎和Struts框架的freemarker模板类似,可以作为mvc的web应用的view层。
    Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代jsp。
    spring Boot
    通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置。
    通过ThymeleafAutoConfiguration类对集成所需要的bean进行自动配置。包括templateResolver,templateEngine,thymeleafViewResolver的配置。

    1.pom.xml中添加

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    自动下载thymeleaf的jar包,然后update Project.

    2.application.properties中添加thymeleaf配置文件

    #Thymeleaf
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.encoding=UTF-8
    # ;charset=<encoding> is added
    #spring.thymeleaf.content-type=text/html
    #set to false for hot refresh
    spring.thymeleaf.cache=false 

    3.之后写一个测试

    a.在项目目录下找src/main/resources/templates新建一个dome.html测试网页,注意要在头部引用

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
          xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  ,不然找不到网页。
    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
          xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  
        <head>  
            <title th:text="${title}"></title>  
        </head>  
        <body>    
            <p th:text="${gr}"></p>  
        </body>  
    </html>  

    b.写测试controller层Thymeleaf.class类

    package com.hxzy.myblog.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class Thymeleaf {
         @RequestMapping("/hi")
         public String helloHtml(Model model){ 
             model.addAttribute("title","Thymeleaf");
             model.addAttribute("gr","大家好");
             return "dome";
         }
    }

    4.总结:

    1.注意html中标签必须严格闭合

    2.html中一对标签中使用thymeleaf,用th:text="${title}",title就加在标签内,如

    <title th:text="${title}"></title> 。
  • 相关阅读:
    (JS/JQ)与Ajax
    JS与JQ的DOM处理
    正则表达式
    JS事件大全
    CSS(初级)学习笔记
    HTML学习笔记
    leetcode记录——65. 有效数字
    dp专题
    Hackerrank---A stones game
    组合博弈问题
  • 原文地址:https://www.cnblogs.com/feipengting/p/7765527.html
Copyright © 2011-2022 走看看