SpringBoot integrated template engine (Thymeleaf, Freemarker, JSP)

Summary of Java knowledge points: If you want to see it, you can enter it from here

2.7. Integrated template engine

2.7.1、Thymeleaf

1 Introduction

Separation of front-end and back-end can be said to be the most mainstream idea today (the front-end writes the front-end code, and the back-end writes the back-end code, without affecting each other).

In traditional Java Web development, JSP is usually used to develop the front page. But the JSP page is written with HTML+Java, which obviously does not conform to the idea of ​​"separation of front and back end". Therefore, in the current Java Web development, the use of JSP has gradually become smaller. Among them, Thymeleaf is one of the better technologies used instead of JSP.

Thymeleaf It is a template engine framework for rendering XML, XHTML, HTML5, JavaScript, CSS and even plain text. It can be integrated with Web frameworks such as Spring MVC, and can be opened directly by the browser even if the project is not running, but the browser will ignore the undefined Thymeleaf tag attributes, and display the effect of a static page. As long as it is accessed through a Web application, Thymeleaf will display It will dynamically replace the static content and make the page display dynamically.

  • Combination of dynamic and static: You can directly open it with a browser to view the static effect of the page, or access it through a Web application to view the dynamic page effect.
  • Out of the box: Provides Spring standard dialect and an optional module perfectly integrated with SpringMVC, which can quickly implement functions such as form binding, attribute editor, and internationalization.
  • Multi-dialect support: It provides Thymeleaf standard and Spring standard two dialects, which can directly apply templates to implement JSTL and OGNL expressions; developers can also expand and create custom dialects when necessary.
  • Perfect integration with SpringBoot: Springboot is officially recommended and supported, and provides default configuration for Thymeleaf, and also sets a view resolver for Thymeleaf.

Using Thymeleaf in Spring requires importing related dependencies (jar packages):

<!--  thymeleaf的依赖  -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.15.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.15.RELEASE</version>
</dependency>
<!--  html、xml解析器-->
<dependency>
    <groupId>org.attoparser</groupId>
    <artifactId>attoparser</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>
<!--转义反转义词库-->
<dependency>
    <groupId>org.unbescape</groupId>
    <artifactId>unbescape</artifactId>
    <version>1.1.6.RELEASE</version>
</dependency>
2. Grammar

Learning from official documents

There are many tags inside Thymeleaf that replace HTML, as well as some expressions. It is these tags and expressions that enable Thymeleaf to have the function of dynamic display.

When using it, add a statement space on the HTML page to avoid errors when editing.

<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • th tag: The reason why thymeleaf can achieve different static and dynamic displays is that it expands the th attribute on the basis of HTML tags. Basically, the attributes of the original HTML tags can be replaced by the th: attribute. These attributes with th can be used directly in HTML tags, so the HTML in Thymeleaf displays the original content when it is static, and displays the content set with attributes after web access, so that it makes HTML dynamic and static two-way display

    Attributes describe example
    th:id Replace HTML's id attribute < input id=“html-id” th:id=“thymeleaf-id” />
    th:text Set the text content of the current element (without escaping html tags) < h1 th:text=“helloSpringBoot” >hello< /h1 >
    th:utext Text replacement without escaping special characters (HTML tags can be recognized) <div th:utext="'<h1>Display</h1>'" >Text</div>
    th:object Select the object in the parent tag, and use the *{…} selection expression to select the attribute value of the object in the child tag. If there is no selection object, the selection expression used in the subtag has the same effect as the ${…} variable expression. At the same time, even if an object is selected, variable expressions can still be used in subtags. < div th:object=“${session.user}” >
    < p th:text=“*{name}”>< /p>
    </ div>
    th:value Replace the value attribute < input th:value = “${user.name}” />
    th:with local variable assignment < div th:with=“isEvens = p r o d S t a t . c o u n t {prodStat.count}%2 == 0" th:text=" prodStat.count{isEvens}”>< /div>
    th:style set style < div th:style=“‘color:#F00; font-weight:bold’”>< /div>
    th:onclick click event < td th:onclick = “‘getInfo()’”>< /td>
    th:each Traverse, support Iterable, Map, array, etc. < table>
    < tr th:each=“m: s e s s i o n . m a p " > < b r / > < t d t h : t e x t = " {session.map}"> <br /> < td th:text=" session.map"><br/><t d t h:text="{m.getKey()}”>< /td>
    < td th:text=“${m.getValue()}”>< /td>
    < /tr>
    < /table>
    th:if Determine whether to display this label according to the conditions < a th:if =“${userId == collect.userId}”>
    th:unless Contrary to th:if judgment, it will not be displayed when the condition is met < div th:unless=“${m.getKey()==‘name’}” >< /div>
    th:switch Similar to Java's switch case statement, usually used in conjunction with th:case < div th:switch=“${name}”>
    < span th:case=“值1”>< /span>
    < span th:case=“值2”>< /span>
    </ div>
    th:selected select selection box selected < select>
    < option th:selected=“${name==‘a’}”> < /option>
    ……
    < /select>
    th:src Replace src attribute in HTML < img th:src=“@{}” src=“” />
    th:action Replace form submission address < form th:action=“@{/user/login}” th:method=“post”> < /form>
    th:inline Inline attribute; This attribute has three values: text, none, and javascript. When used in the <script> tag, the js code can get the object of the page passed in the background.
    th:replace Layout tag; replaces the current entire tag with the template fragment (containing tag) specified by the th:fragment attribute.
    th:insert Layout tag; inserts the template fragment (containing tag) specified using the th:fragment attribute into the current tag.
    th:fragment Template layout, similar to JSP tags, used to define a template fragment that is referenced or included
  • expression:

    • Variable expression: ${}The expression wrapped by ${} is a variable expression

      • Get the properties and methods of the object: the controller sends a student object

        获取学生的id:${student.getId}
        
      • Use built-in primitives

        • #ctx : context object

        • #vars : context variables

        • #locale: the locale of the context

        • #request: available in web applications (server: setAttribute(“student”, student))

          ${request.getAttribute('student')}
          
        • #response: Available in the web app

        • #session: available in web applications

        • #servletContext: available in web applications

      • Use built-in tool objects

        • strings, numbers, arrays, collections, dates, etc.

          ${#strings.equals(o1,o2}
          
    • Select variable expression: *{} (basically the same function as variable expression, but can be used with th:object, after th:object stores an object, the object can be obtained in its internal subtag)

    • Internationalization: #{} (you can get internationalized configuration)

    • Link URL expression: refer to other links (static resources, form form requests, a tags, etc.)

      • Request without parameters: @{xxx}
      • There is a request for participation: @{/xxx(k1=v1,k2=v2)}
    • Fragment expression: ~ (used to refer to other template fragments in the template page)

  • letter

    • 文本字面量:'one text', 'Another one!', …
    • 数字字面量:0, 34, 3.0, 12.3,…
    • 布尔文字:true,false
    • 空字面量: null
    • 文字标记:one, sometext, main,…
  • 文本操作:

    • 字符串连接: +
    • 字面替换: |The name is ${name}|
  • 算术运算:

    • 二元运算符:+, -, *, /,%
    • 减号(一元运算符): -
  • 布尔运算:

    • 二元运算符:and,or
    • 布尔否定(一元运算符):!,not
  • 比较与相等:

    • 比较器:>, <, >=, <=( gt, lt, ge, le)
    • 等式运算符:==, !=( eq, ne)
  • 条件运算符:

    • 如果-那么: (if) ? (then)
    • 如果-然后-其他: (if) ? (then) : (else)
    • 默认: (value) ?: (defaultvalue)
3、使用

Spring Boot 推荐使用 Thymeleaf 作为其模板引擎。SpringBoot 为 Thymeleaf 提供了一系列默认配置,项目中一但导入了 Thymeleaf 的依赖,相对应的自动配置 (ThymeleafAutoConfiguration 或 FreeMarkerAutoConfiguration) 就会自动生效,因此 Thymeleaf 可以与 Spring Boot 完美整合 。

Spring Boot 整合 Thymeleaf 模板引擎,需要以下步骤:

  1. 引入 Starter启动器

    <!--thymeleaf模板的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 其模板引擎大多都使用默认值,不配置也能直接使用

    image-20220920165656447
  3. 通过controller访问

    image-20210825115440665 image-20210825115459154 image-20210825115512450

2.7.2、Freemarker

一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 是一种用Java语言编写的模板引擎,与Web容器无关,在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生产XML,JSP或Java等。目前企业中主要用Freemarker做静态页面或是页面展示

freemarker并不关心数据的来源,只是根据模板的内容,将数据模型在模板中显示并输出文件

  • 添加Freemarker 的依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    
  • yml中配置

    spring:
      freemarker:
        cache: false
        charset: utf-8
        template-loader-path: classpath:/templates/
        suffix: .html
        content-type: text/html
        request-context-attribute: request
    
  • html页面

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>FreeMarker</title>
        </head>
        <body>
            <h1>Welcome ${user} !</h1>
    
            <u1>
                <#list lists as list>
                    <li>${list} </li>
                </#list>
             </u1>
         </body>
    </html>
    

2.7.3、整合JSP

SpringBoot默认是不支持JSP模板引擎的,但是可以通过引入相关依赖来整合JSP模板引擎。

  • 导入支持JSP的依赖

     <!-- 内置的不支持jsp,所以要添加支持jsp的tomcat-->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <!--jsp标签库支持-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    
  • 添加webapp文件

    image-20210908155559672
  • yml文件中配置支持jsp页面

    spring: 
     mvc:    #支持的jsp路径
        view:
          prefix: /WEB-INF/
          suffix: .jsp
    

Guess you like

Origin blog.csdn.net/yuandfeng/article/details/129709546