鍍金池/ 教程/ Java/ Thymeleaf字符串轉(zhuǎn)義
Thymeleaf Servlet Hellow World示例
Thymeleaf表單
Thymeleaf字符串連接
Thymeleaf項(xiàng)目實(shí)踐
Thymeleaf字符串轉(zhuǎn)義
Thymeleaf擴(kuò)展2(Say Hello)
Thymeleaf標(biāo)準(zhǔn)方言
Thymeleaf條件判斷
Thymeleaf擴(kuò)展
Thymeleaf簡(jiǎn)單格式化輸出
Thymeleaf簡(jiǎn)介
Thymeleaf顯示Bean的值
Thymeleaf教程
Thymeleaf Spring表達(dá)式語(yǔ)言
Thymeleaf迭代列表
Thymeleaf+SpringMVC5示例
Thymeleaf標(biāo)準(zhǔn)URL語(yǔ)法

Thymeleaf字符串轉(zhuǎn)義

本文章將介紹Thymeleaf標(biāo)準(zhǔn)表達(dá)式語(yǔ)法中的概念。

  • 學(xué)習(xí)如何在Thymeleaf模板中顯示轉(zhuǎn)義值。
  • 已將HTML代碼片段設(shè)置為上下文模型,并將其作為變量名為html的字符串。在第一個(gè)div中顯示HTML轉(zhuǎn)義字符串,在第二個(gè)div中顯示未轉(zhuǎn)義字符串。

如果要上機(jī)實(shí)踐,請(qǐng)參考:Thymeleaf+SpringMVC5示例項(xiàng)目。這里不再重復(fù)創(chuàng)建項(xiàng)目的過(guò)程,這里將只介紹如何使用Thymeleaf標(biāo)準(zhǔn)表達(dá)式和標(biāo)簽。

這里創(chuàng)建一個(gè)Maven Web項(xiàng)目: thymeleaf-tutorials ,其目錄結(jié)構(gòu)如下所示 -

控制器類的實(shí)現(xiàn):MyController.java -

package com.yiibai.spring.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.yiibai.spring.bean.Product;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) throws ParseException {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
      model.addAttribute("product", product);
      return "index";
   }

   @GetMapping("/escape")
   public String escape(Model model) throws ParseException {
     String html =  "Welcome to our <b>fantastic</b> grocery store!";
      model.addAttribute("html", html);
      return "escape";
   }
}

模板文件的實(shí)現(xiàn):/webapp/WEB-INFO/views/escape.html -

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf示例</title>
</head>
<body>
    <h2>Spring MVC5 + Thymeleaf 字符串轉(zhuǎn)義示例</h2>
    <div th:text="${html}">Some escaped text</div>
    <div th:utext="${html}">Some unescaped text</div>
</body>
</html>

運(yùn)行上面項(xiàng)目,在瀏覽器中顯示效果如下 -