第3讲 显示带标签的文本

在正规的开发环境下,控制器所传递过来的内容只有核心文本,但是能不能传递带有样式或者html标签的数据呢?

编写一个控制器方法:

       @RequestMapping(value = "/message/showStyle", method = RequestMethod.GET)

       public String showStyle(Model model) { // 通过model可以实现内容的传递

              model.addAttribute("url", "<span style='color:red'>www.bonc.cn</span>"); // request属性传递包装

              return "message/message_show_style";

       }

编写message/ message_show_style.html 页面,

<!DOCTYPE HTML>

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

<head>

       <title>SpringBoot模版渲染</title>

       <link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>

       <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

</head>

<body>

       <p th:text="'官方网站:' + ${url}"/>

</body>

</html>

浏览器输入:http://127.0.0.1:8080/message/showStyle  页面效果:

第3讲 显示带标签的文本

现在使用utext 标签,

<!DOCTYPE HTML>

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

<head>

       <title>SpringBoot模版渲染</title>

       <link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>

       <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

</head>

<body>

       <p th:text="'官方网站:' + ${url}"/>

       <p th:utext="'官方网站:' + ${url}"/>

</body>

</html>

显示:

第3讲 显示带标签的文本

从安全角度来讲,肯定使用“th:text”来显示信息才安全,可以防止脚本攻击