SpringBoot模板引擎

测试是否springboot集成是否成功

在这里插入图片描述
相当与集成mybatis

ThymeleafController

package com.wxm.springboot.controller.springboot2;

import com.wxm.springboot.entity.springboot2.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wxm
 * @site www.wxm.com
 * @company xxx公司
 * @create 2019-12-28 15:57
 */

@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    @RequestMapping("/list")
        public String  list() {
        System.out.println(" list........");
        return  "list";
    }
}

http://localhost/thymeleaf/list

在这里插入图片描述

thymeleaf模板

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

这里讲解的时候的时候是关闭缓存的(不关闭缓存有可能存在代码没有显示效果的问题)

将配置文件的后缀名改成.yml文件
在这里插入图片描述

spring.thymeleaf.cache=false

直接使用el表达式:${title},这里如果是支持的时候是会显示出人员表这几个字

在这里插入图片描述
显然不支持,因为这里使用的是html,而不是jsp,${xxx}是jstl表达式,必须基于jsp,

thymeleaf中${}语法

<h3 th:text="${title}"></h3>

在这里插入图片描述

thymeleaf中list遍历

  <tr th:each="u : ${userList}">
        <td th:text="${u.uid}">
        </td>
        <td th:text="${u.uname}">
        </td>
        <td th:text="${u.upwd}">
        </td>
    </tr>

在这里插入图片描述
在这里插入图片描述

thymeleaf解决html转译问题

html

<p th:utext="${msg}"></p>

controller
在这里插入图片描述
效果:
在这里插入图片描述

Freemarker模板

性能优化会选择Freemarker模板
学习网站:http://freemarker.foofun.cn/

Freemarker中获取单个值写法html

直接使用el表达式:${title},这里如果是支持的时候是会显示出人员表这几个字

Freemarker中条件语法html

<#if sex=='girl'>
女
<#elseif sex=='boy'>
男
<#else>
保密
</#if>

Freemarker中 exists用在逻辑判断html

<h3>exists用在逻辑判断</h3>
<#if name?exists>
    ${name}
</#if>

Freemarker中 list 循环html

<h2>循环</h2>
<table border="1px" width="600px">
    <thead>
    <tr>
        <td>ID</td>
        <td>角色名</td>
        <td>描述</td>
    </tr>
    </thead>
    <tbody>
    <#list roles as role>
    <tr>
        <td>${role.rid}</td>
        <td>${role.rname}</td>
    </tr>
    </#list>
    </tbody>
</table>

Freemarker中 局部变量(assign)/全局变量(global)html

<h2>局部变量(assign)/全局变量(global)</h2>
<#--获取全路径名${pageContext.request.contextpath}-->
<#assign ctx1>
    ${springMacroRequestContext.contextPath}
</#assign>

<#global ctx2>
    ${springMacroRequestContext.contextPath}
</#global>

pom

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
   </dependency>

<!--可以不加,但是做项目的时候可能会用-->
 <resources>
            <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--freemarker模板也读取需要注释标红地方-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <!--<include>*.properties</include>-->
                    <!--<include>*.xml</include>-->
                    <!--<include>*.yml</include>-->
                </includes>
            </resource>
        </resources>

application.yml文件的默认配置

server:
  port: 80
  servlet:
    context-path: /

spring:
  thymeleaf:
    cache: false

  freemarker:
    # 设置模板后缀名
    suffix: .ftl
    # 设置文档类型
    content-type: text/html
    # 设置页面编码格式
    charset: UTF-8
    # 设置页面缓存
    cache: false
    # 设置ftl文件路径,默认是/templates,为演示效果添加role
    template-loader-path: classpath:/templates/role
  mvc:
    static-path-pattern: /static/**

注意层级关系

相当与

springmvc.xml
     internalResouresviewResolver
         prefix  classpath:/templates/role
          subfix  .ftl

配置freemarker。也可不配置,则创建ftl文件时改后缀名
在这里插入图片描述

Role

package com.wxm.springboot.entity.springboot2;

/**
 * @author wxm
 * @site www.wxm.com
 * @company xxx公司
 * @create 2019-12-30 8:19
 */
public class Role {
    private String rid;
    private String rname;

    public Role(String rid, String rname) {
        this.rid = rid;
        this.rname = rname;
    }

    public Role() {
    }



}

RoleController

package com.wxm.springboot.controller.springboot2;

import com.wxm.springboot.entity.springboot2.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wxm
 * @site www.wxm.com
 * @company xxx公司
 * @create 2019-12-30 8:19
 *
 *介绍Thymeleaf模板的应用
 *
 */
@Controller
@RequestMapping("/freemarker")
public class RoleController {
    @RequestMapping("/list")
    public ModelAndView list(){
        System.out.println("这是list");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("freemarklist");
        mv.addObject("name","张三");
        mv.addObject("sex","gay");

        List<Role> list = new ArrayList();
        list.add(new Role("1","超级会员"));
        list.add(new Role("2","会员"));
        list.add(new Role("3","普通用户"));
        mv.addObject("roles",list);

        return  mv;
    }

}

注意application.yml的配置一致性
在这里插入图片描述
freemarklist.ftl

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Freemarker模板知识点</title>
</head>
<body>
<h2>取值</h2>
<h3>提供默认值</h3>
welcome 【${name!'未知'}】 to freemarker!

<h3>exists用在逻辑判断</h3>
<#if name?exists>
    ${name}
</#if>

<h2>条件</h2>
<#if sex=='girl'><#elseif sex=='boy'><#else>
保密
</#if>

<h2>循环</h2>
<table border="1px" width="600px">
    <thead>
    <tr>
        <td>ID</td>
        <td>角色名</td>
        <td>描述</td>
    </tr>
    </thead>
    <tbody>
    <#list roles as role>
    <tr>
        <td>${role.rid}</td>
        <td>${role.rname}</td>
    </tr>
    </#list>
    </tbody>
</table>

<h2>include</h2>
<#include 'foot.ftl'>

<h2>局部变量(assign)/全局变量(global)</h2>
<#--获取全路径名${pageContext.request.contextpath}-->
<#assign ctx1>
    ${springMacroRequestContext.contextPath}
</#assign>

<#global ctx2>
    ${springMacroRequestContext.contextPath}
</#global>

${ctx1}------${ctx2}
</body>
</html>


解决报错:缺失实体类get.set问题

FreeMarker template error (DEBUG mode; use RETHROW in production!): The following has evaluated to null or missing: ==> role.rid [in template “freemarklist.ftl” at line 38, column 15] ---- Tip: It’s the step after the last dot that caused this error, not those before it. ---- Tip: If the failing expression is known to legally refer to something that’s sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: r o l e . r i d [ i n t e m p l a t e " f r e e m a r k l i s t . f t l " a t l i n e 38 , c o l u m n 13 ] J a v a s t a c k t r a c e ( f o r p r o g r a m m e r s ) : f r e e m a r k e r . c o r e . I n v a l i d R e f e r e n c e E x c e p t i o n : [ . . . E x c e p t i o n m e s s a g e w a s a l r e a d y p r i n t e d ; s e e i t a b o v e . . . ] a t f r e e m a r k e r . c o r e . I n v a l i d R e f e r e n c e E x c e p t i o n . g e t I n s t a n c e ( I n v a l i d R e f e r e n c e E x c e p t i o n . j a v a : 134 ) a t f r e e m a r k e r . c o r e . E v a l U t i l . c o e r c e M o d e l T o T e x t u a l C o m m o n ( E v a l U t i l . j a v a : 479 ) a t f r e e m a r k e r . c o r e . E v a l U t i l . c o e r c e M o d e l T o S t r i n g O r M a r k u p ( E v a l U t i l . j a v a : 401 ) a t f r e e m a r k e r . c o r e . E v a l U t i l . c o e r c e M o d e l T o S t r i n g O r M a r k u p ( E v a l U t i l . j a v a : 370 ) a t f r e e m a r k e r . c o r e . D o l l a r V a r i a b l e . c a l c u l a t e I n t e r p o l a t e d S t r i n g O r M a r k u p ( D o l l a r V a r i a b l e . j a v a : 100 ) a t f r e e m a r k e r . c o r e . D o l l a r V a r i a b l e . a c c e p t ( D o l l a r V a r i a b l e . j a v a : 63 ) a t f r e e m a r k e r . c o r e . E n v i r o n m e n t . v i s i t ( E n v i r o n m e n t . j a v a : 367 ) a t f r e e m a r k e r . c o r e . I t e r a t o r B l o c k {role.rid} [in template "freemarklist.ftl" at line 38, column 13] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:479) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:367) at freemarker.core.IteratorBlock IterationContext.executedNestedContentForCollOrSeqListing(IteratorBlock.java:321) at freemarker.core.IteratorBlock I t e r a t i o n C o n t e x t . e x e c u t e N e s t e d C o n t e n t ( I t e r a t o r B l o c k . j a v a : 271 ) a t f r e e m a r k e r . c o r e . I t e r a t o r B l o c k IterationContext.executeNestedContent(IteratorBlock.java:271) at freemarker.core.IteratorBlock IterationContext.accept(IteratorBlock.java:244) at 在这里插入图片描述

解决报错ftl文件没有在application.xml对应得位置下

FreeMarker template error (DEBUG mode; use RETHROW in production!): Template inclusion failed (for parameter value “…/foot.ftl”): Template not found for name “…/foot.ftl”. Reason given: Backing out from the root directory is not allowed. The name was interpreted by this TemplateLoader: MultiTemplateLoader(loader1 = FileTemplateLoader(baseDir=“E:\重要备份\idea1122\springboot\target\classes\templates\role”, canonicalBasePath=“E:\重要备份\idea1122\springboot\target\classes\templates\role”), loader2 = ClassTemplateLoader(resourceLoaderClass=org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer, basePackagePath="" /* relatively to resourceLoaderClass pkg */)). ---- FTL stack trace ("~" means nesting-related): - Failed at: #include “…/foot.ftl” [in template “freemarklist.ftl” at line 46, column 1] ---- Java stack trace (for programmers): ---- freemarker.core._MiscTemplateException: [… Exception message was already printed; see it above …] at freemarker.core.Include.accept(Include.java:164) at freemarker.core.Environment.visit(Environment.java:331) at freemarker.core.Environment.visit(Environment.java:337) at freemarker.core.Environment.process(Environment.java:310) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:391) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:304) at
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

完整效果

在这里插入图片描述

发布了100 篇原创文章 · 获赞 8 · 访问量 4109

猜你喜欢

转载自blog.csdn.net/weixin_44106334/article/details/103747942