thymeleaf 模板引擎

1.创建模板解析器 Create Template Resolver  用来加载模板

1 // create template resolver
2 //创建模板解析器可以用Servlet上下文模板解析器ServletContextTemplateResolver或者类加载模板解析器ClassLoaderTemplateResolver
3
4 ServletContextTemplateResolver  templateResolver = new ServletContextTemplateResolver();
5 ClassLoaderTemplateResolver  templateResolver = new ClassLoaderTemplateResolver();

创建模板解析器将指定我们从Servlet上下文检索模板文件作为资源,并考虑应用程序的根路径作为资源的路径。如下:

1 // XHTML is the default mode, but we will set it anyway for better understanding of code
2 templateResolver.setTemplateMode(‘XHTML‘);
3
4 // This will convert "home" to "/WEB-INF/templates/home.html"
5 templateResolver.setPrefix(‘/WEB-INF/templates/‘);
6 templateResolver.setSuffix(‘.html‘);

如上所示,通过解析器创建模板节点,当使用Thymeleaf渲染名为“home”的模板的的时候,将,解析器将会自动加上前缀和后缀(扩展名)。

2.创建模板引擎 Create Template Engine

1 //Create Template Engine
2 TemplateEngine templateEngine = new TemplateEngine();
3 templateEngine.setTemplateResolver(templateResolver);  //设置模板解析器

创建模板引擎很简单,只需要一个模板解析器实例。创建了关键的模板解析器和模板引擎之后,我们就可以创建模板页面使用Thymeleaf。

3.创建模板文件

模板文件放在‘/WEB-INF/templates/‘路径下。要指定DOCTYPE和命名空间。

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello thymeleaf</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p>
      <span th:text="#{home.welcome}">this is text will not be show</span>
    </p>
  </body>
</html>

模板文件中的th:text”属性的值是一个变量表达式,它将获取变量“hellword”的值作为<span>标签的文本显示到页面上。

4.创建模板上下文

为了输出变量“helloworld”的值,我们需要创建模板上下文,将变量输出到模板文件中。

//create servlet context
WebContext ctx = new WebContext(req,resp,this.getServletContext(),req.getLocale());
ctx.setVariable(‘helloword‘,‘hello thymeleaf,wellcome!‘)

5.执行模板引擎

执行模板引擎需要传入模板名、上下文对象以及响应流。如下:

 //Executing template engine
templateEngine.process(‘home‘,ctx,resp.getWriter());

让我们看看执行模板引擎后的结果:

OK,如上所说,模板文件被替换成了标准的XHTML文件了。

最后的源码

public class thymeleafServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //Create Template Resolver
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        //ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode("XHTML");
        // This will convert "home" to "/WEB-INF/templates/home.html"
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
        // Cache is set to true by default. Set to false if you want templates to
        // be automatically updated when modified.
        templateResolver.setCacheable(true);
        //Create Template Engine
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        //Write the response headers
        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        //Create Servlet context
        WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());
        ctx.setVariable("helloword","hello thymeleaf,wellcome!");

        //Executing template engine
        templateEngine.process("home", ctx, resp.getWriter());
    }
}

原文地址:http://www.mamicode.com/info-detail-1150559.html

时间: 2024-08-28 08:51:31

thymeleaf 模板引擎的相关文章

Thymeleaf模板引擎使用

Thymeleaf模板引擎使用 什么是Thymeleaf Thymeleaf是一个Java库.它是一个XML / XHTML / HTML5模板引擎,能够在模板文件上应用一组转换,将程序产生的数据或者文本显示到模板文件上. Thymeleaf依赖的jar包 要使用Thymeleaf,需要在我们的web应用的classpath路径中引入相关的jar,如下: thymeleaf-2.1.3.RELEASE.jarognl-3.0.6.jarjavassist-3.16.1-GA.jarunbesca

Thymeleaf模板引擎的初步使用

在springboot中,推荐使用的模板引擎是Thymeleaf模板引擎,它提供了完美的Spring MVC的支持.下面就简单的介绍一下Thymeleaf模板引擎的使用. 在controller层中,使用在类上使用@controller注解,注意的是,这里不是@restController注解,因为@restController注解是将结果作为json字符串进行返回的,并不是调用模板. 方法中,注入参数,Model model.然后同springmvc中的modelandview一样,model

spring boot Thymeleaf模板引擎 最简单输出例子

spring boot  Thymeleaf模板引擎  最简单输出例子 控制器代码如下: @GetMapping(value = "/test")public String test(Model model){ List<Boy> boy = new ArrayList<Boy>(); boy.add(new Boy("xx",11)); boy.add(new Boy("yy",22)); boy.add(new Boy

jdbcTemplate 和 Thymeleaf模板引擎 查询 到模板赋值例子

二.  jdbcTemplate 和 Thymeleaf模板引擎  最简单输出例子 控制器代码 @GetMapping(value = "/test2") public String test2(Model model){ sql = "SELECT * FROM boy "; List queryList = jdbcTemplate.queryForList(sql); model.addAttribute("boy", queryList)

SpringBoot入门篇--使用Thymeleaf模板引擎进行页面的渲染

在做WEB开发的时候,我们不可避免的就是在前端页面之间进行跳转,中间进行数据的查询等等操作.我们在使用SpringBoot之前包括我在内其实大部分都是用的是JSP页面,可以说使用的已经很熟悉.但是我们在使用springBoot开发框架以后我们会发现一个致命的问题,就是SpringBoot对Jsp的支持可以说是惨不忍睹,官方推荐我们进行使用的是Thymeleaf模板引擎进行.其实我这里也没搞清楚模板引擎原理是什么,以后有机会再深入了解,我们只需要学会怎么用就行,目前而言.当然模板引擎有很多,比如f

(二)SpringBoot基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

一.描述 在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等): 并且SpringBoot内置了Thymeleaf模板引擎,可以使用模板引擎进行渲染处理,默认版本为2.1,可以重新定义Thymeleaf的版本号,在maven的配置文件中配置如下内容: <properties> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> &l

SpringBoot使用thymeleaf模板引擎

(1).添加pom依赖 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-thymeleaf</artifactId> 4 </dependency> * SpringBoot1.x 默认的thymeleaf版本低,如果要自定义版本,需要在pom properties 覆写SpringBoot默认

Thymeleaf 模板引擎简介

目录 Thymeleaf 模板引擎 官方文档下载 Hello World 新建应用 后台控制器 前端页面 浏览器访问测试 Thymeleaf 模板引擎1.Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本. 2.Thymeleaf 的主要目标是提供一种优雅和高度可维护的创建模板的方式.为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型.这改善了设计的沟通,弥补

SpringBoot 配置 Thymeleaf模板引擎

Thymeleaf模板引擎 什么是模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档. 学习视频: http://www.itlaoqi.com/chapter/1688.html 源码地址: QQ群 814077650 , 群共享中自助下载 老齐的官网: itlaoqi.com (更多干货就在其中) Thymeleaf的特点 Thymeleaf优点 主流唯一的前后端通用

SpringBoot:2.SpringBoot整合Thymeleaf模板引擎渲染web视图

在Web开发过程中,Spring Boot可以通过@RestController来返回json数据,那如何渲染Web页面?Spring Boot提供了多种默认渲染html的模板引擎,主要有以下几种: Thymeleaf FreeMarker Velocity Groovy Mustache Spring Boot 推荐使用这些模板引擎来代替 Jsp,Thymeleaf 只是其中一种,下面我们来简单聊聊Thymeleaf及实践一下如何整合Spring Boot和Thymeleaf. 1.Thyme