SpringBoot优化之——1.Thymeleaf 配置等注意事项

Thymeleaf

Thymeleaf简介

Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。
Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。需要注意的是thymeleaf不是spring旗下的。这里我们使用thymeleaf 3版本。

第一个thymeleaf程序


添加thymeleaf依赖

    org.springframework.boot
    spring-boot-starter-thymeleaf


修改spring boot配置文件

在开发阶段,建议关闭thymeleaf的缓存(在application.properties文件中设置)

spring.thymeleaf.cache=false


thymeleaf会对html中的标签进行严格校验,如果html标签缺少结束标签的话,thymeleaf会报错,我们可以通过下面方式去除thymeleaf的校验,添加依赖:

 
      net.sourceforge.nekohtml
      nekohtml
      1.9.22
   


在spring boot配置文件中添加下面内容:

spring.thymeleaf.mode=LEGANCYHTML5


创建controller准备数据

package com.chen.pj.health.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller //bean对象
public class TemplateController { //在spring mvc中这个对象称之为handler(处理器)
 //访问:  http://localhost/doTemplateUI
 @RequestMapping("doTemplateUI")
    public String doTemplateUI(){ //@RequestMapping用于定义url请求的映射
 return "default";  //view name(视图名)
 //1 这名字返回给谁了?方法的调用者(调用者是---DispatcherServlet)
 //2 DispatcherServlet拿到viewname 以后做什么(交给师徒解释器进行解析-->前缀,后缀,数据)
 //3 将拿到的view解析结果响应到客户端(/templates/default.html)
 }
}

**创建html页面

在resources/templates里面创建一个index.html,填写下面内容**




    
    Title


The Default Template page!!!! 已更改/再次更改

Springboot使用thymeleaf作为视图展示的时候,我们将模板文件放置在resource/templates目录下,静态资源放置在resource/static目录下



表达式

标准变量表达式

创建用来准备数据的Controller

package com.chen.pj.module.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ModelViewController {
    @RequestMapping("/doModelAndView")
    public String doModelAndView(Model model){
        // 参数model由spring web模块创建,可以存储一些数据
 model.addAttribute("username","chenhao");
        model.addAttribute("state","perfect");
        return "view"; //viewname
 // 这里的响应结果,会在spring mvc中会帮我们封装为ModelAndview对象
 }
    @RequestMapping("/doModelAndView02")
    public ModelAndView doModelAndView(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("username","chenhao02");
        mv.addObject("state","ok02");
        mv.setViewName("view");
        return mv;
    }
}


选择变量表达式



    
    Title


    

The view page

  • username:[[${username}]]
  • state:[[${state}]]

运行程序,登录网页后显示如图:
SpringBoot优化之——1.Thymeleaf 配置等注意事项_第1张图片

你可能感兴趣的:(java,thymeleaf)