一些常见的模板引擎

JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推荐的Thymeleaf,语法更简单,功能更强大。

SpringBoot 引入 thymeleaf

pom文件中添加依赖

        <!--引入thymeleaf模块引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

thymeleaf官网

SpringBoot 使用 thymeleaf

查看SpringBoot自动配置源码

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

	private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染

1、导入thymeleaf的名称空间 :在HTML文件的<html>标签中添加属性:xmlns:th="http://www.thymeleaf.org"

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2、编写Controller跳转到页面

    /**
     * @return 跳转到classpath:/templates/success.html
     */
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("who","moti");
        return "success";
    }

3、编写html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--th:text 将div里面的文本内容设置为 -->
    <h1>欢迎你,<span th:text="${who}"></span>!</h1>
</body>
</html>

thymeleaf 语法规则

1、标签优先级

  • th:text 改变当前元素里面的文本内容
  • th:任意html属性 来替换原生属性的值

2、表达式

  • 2.1 Simple expressions(简单表达式):
    • Variable Expressions: ${…} 变量表达式
    1. 获取对象的属性、调用方法
    2. 使用内置的基本对象
    3. 使用内置的一些工具对象
    # 内置基本对象
                #ctx : the context object.
                #vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.          
                #response : (only in Web Contexts) the HttpServletResponse object.             
                #session : (only in Web Contexts) the HttpSession object.             
                #servletContext : (only in Web Contexts) the ServletContext object.
    # 内置的一些工具对象 
                execInfo : information about the template being processed.
                messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
                uris : methods for escaping parts of URLs/URIs
                conversions : methods for executing the configured conversion service (if any).
                dates : methods for java.util.Date objects: formatting, component extraction, etc.
                calendars : analogous to #dates , but for java.util.Calendar objects.
                numbers : methods for formatting numeric objects.
                strings : methods for String objects: contains, startsWith, prepending/appending, etc.
                objects : methods for objects in general.
                bools : methods for boolean evaluation.
                arrays : methods for arrays.
                lists : methods for lists.
                sets : methods for sets.
                maps : methods for maps.
                aggregates : methods for creating aggregates on arrays or collections.
                ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    • Selection Variable Expressions: *{…} 选择变量表达式 :和${}在功能上是一样

    补充:配合 th:object="${session.user}

    <div th:object="${session.user}">
        <p>Name: <span th:text="*{userName}">Sebastian</span>.</p>
        <p>Age: <span th:text="*{age}">Pepper</span>.</p>
        <p>Sex: <span th:text="*{sex}">Saturn</span>.</p>
    </div>
    • Message Expressions: #{…} 消息表达式 :获取国际化内容
    <h1 th:text="#{login.tip}">Please sign in</h1>
    • Link URL Expressions: @{…} 链接URL表达式 :定义URL
    @{/order/process(execId=${execId},execType='FAST')}
    • Fragment Expressions: ~{…} 片段表达式
    <div th:insert="~{commons :: main}">...</div>

  • 2.2 Literals(字面量)
  •        Text literals: 'one text' , 'Another one!' ,…
           Number literals: 0 , 34 , 3.0 , 12.3 ,…
           Boolean literals: true , false
           Null literal: null
           Literal tokens: one , sometext , main ,…

  • 2.3 Text operations(文本操作)
  •      String concatenation: +
         Literal substitutions: |The name is ${name}|

  • 2.4 Arithmetic operations(数学运算)
  • Binary operators: + , - , * , / , %
    Minus sign (unary operator): -

  • 2.5 Boolean operations(布尔运算)
  • Binary operators: and , or
    Boolean negation (unary operator): ! , not

  • 2.6 Comparisons and equality(比较运算)
  • Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )

  • 2.7 Conditional operators 条件运算(三元运算符)
  • If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

  • 2.8 Special tokens
  • No-Operation: _ 
    最后修改日期:2020-07-12

    作者

    留言

    This is a great promise and will surely be of great benefit to many in Africa and beyond! Hailee Bob Jarid

    Some really wonderful info , Gladiolus I detected this. Jaclyn Gabriel Rourke

    Major thankies for the article post. Thanks Again. Really Cool. Cicily Peterus Maurreen

    I am not sure where you are getting your information, but great topic. Nari Wesley Kwabena

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?| Nerita Clint Panter

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is wonderful, let alone the content! Adrea Noah Chatterjee

    Hi there Dear, are you in fact visiting this web page regularly, if so afterward you will definitely take nice experience. Jobie Dennie Rona

    Simply desire to say your article is as surprising. The clarity in your post is simply excellent and i could assume you are an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work. Noellyn Elihu Rutherford

    Generally I do not learn post on blogs, however I would like to say that this write-up very forced me to check out and do it! Your writing style has been amazed me. Thank you, very nice post. Mariele Isadore Donny

    If you are going for best contents like I do, only go to see this web page all the time because it presents feature contents, thanks Maribeth Lonnard England

    This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your excellent post. Also, I have shared your website in my social networks!| Damaris Halsey Reagen

    Phasellus ullamcorper ipsum rutrum nunc Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Curabitur turpis. In dui magna, posuere eget, vestibulum et, tempor auctor, justo. Lynett Graig Dino

    When most of your blog is coming from an I, me or you standpoint, it can turn the reader off. Audrie Izzy Jago

    I havent had to plan a family trip with kids yet. I only know of family trips with me being the kid. I didnt realize there was a lot of planning that goes into it! My mother has taken me on a cruise and my dad through different ski resorts. Both to different cities and countries and always around my school break. Modestine Etienne Giliana

    After checking out a few of the blog posts on your web site, I honestly like your way of blogging. I added it to my bookmark site list and will be checking back soon. Take a look at my website as well and let me know how you feel. Tarah Tam Zaneski

    I added a fresh new list of auto approve links to my site. I hope you all can make good use out of these links. Thank you for visiting my site and happy link building! Brit Cesare Grimbly

    撰写回覆或留言

    发布留言必须填写的电子邮件地址不会公开。