欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springboot模块(Freemarker模板和Thymeleaf模板)

程序员文章站 2022-07-10 17:29:59
Springboot模块Thymeleaf模板第一步Thymeleaf模板第一步导入相关pom的依赖 org.springframework.boot spring-boot-starter-thymeleaf ......

Thymeleaf模板

一、Thymeleaf简述

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

1、Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2、Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3、Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

二、简单操作

  1. 导入相关pom的依赖

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
     </dependency>
    
  2. 创建一个entity包,User实体类,

User类

	package com.zking.demo.entity;
	
	import lombok.Data;
	
	/**
	 * @author因果
	 * @site www.xiaomage.com
	 * @company xxx公司
	 * @create  2020-11-27 8:49
	 */
	@Data
	public class User {
	
	    private Integer uid;
	    private String uname;
	    private String pwd;
	
	    public User() {
	    }
	
	    public User(Integer uid, String uname, String pwd) {
	        this.uid = uid;
	        this.uname = uname;
	        this.pwd = pwd;
	    }
	
	}
  1. 在Controller包下创UserControoler类测试

UserControoler

		package com.zking.demo.controller;
		
		import com.zking.demo.entity.User;
		import org.springframework.stereotype.Controller;
		import org.springframework.web.bind.annotation.RequestMapping;
		
		import javax.servlet.http.HttpServletRequest;
		import java.util.ArrayList;
		import java.util.List;
		
		/**
		 * @author因果
		 * @site www.xiaomage.com
		 * @company xxx公司
		 * @create  2020-11-27 8:54
		 */
		@Controller
		@RequestMapping("/User")
		public class UserController {
		
		    @RequestMapping("/list")
		    public String list(HttpServletRequest request){
		        request.setAttribute("msg","传单个字符!!!");
		        List<User>  userList=new ArrayList<>();
		        userList.add(new User(1,"小明","12342"));
		        userList.add(new User(2,"大明","12342"));
		        userList.add(new User(3,"二明","12342"));
		        userList.add(new User(4,"山明","12342"));
		        request.setAttribute("userList",userList);
		        request.setAttribute("htmlStr","<span style='color:red' >转义html代码块</span>");
		        return "list";
		    }
		}

4.创建一个html页面,接受list方法的值。

用<html xmlns:th="http://www.thymeleaf.org"> 替换<html lang="en">

Springboot模块(Freemarker模板和Thymeleaf模板)

  1. 传值jsp页面

list.jsp代码

	<!DOCTYPE html>
	<html xmlns:th="http://www.thymeleaf.org">
	<head>
	    <meta charset="UTF-8">
	    <title>thymeleaf模块知识点接受</title>
	</head>
	<body>
	<div th:text="${msg}"></div>
	    <table width="70%" border="1">
	        <tr>
	            <td>id</td>
	            <td>用户名</td>
	            <td>密码</td>
	        </tr>
	        <tr th:each="u : ${userList}">
	            <td th:text="${u.uid}"></td>
	            <td th:text="${u.uname}"></td>
	            <td th:text="${u.pwd}"></td>
	        </tr>
	    </table>
	<div th:utext="${htmStr}"></div>
	</body>
	</html>

效果图:

Springboot模块(Freemarker模板和Thymeleaf模板)

Thymeleaf的一个好用的功能

新建一个主页面common.html,清空所有的内容,不存任何代码,在添加一下代码

	<div th:fragment="h1">
	    第一部分
	</div>
	<div th:fragment="h2">
	    第二部分
	</div>
	<div th:fragment="h3">
	    第三部分
	</div>

再到list.html页面引用。

  1. 引用整张页面

     <div th:include="common.html"></div>
    

Springboot模块(Freemarker模板和Thymeleaf模板)

  1. 引用部分页面

Springboot模块(Freemarker模板和Thymeleaf模板)

Freemarker模板

  1. pom.xml导入相关依赖

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-freemarker</artifactId>
     </dependency>
    
  2. 这个可以不加,但是做项目的时候可能会用

     	 <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>
    

3.添加一些配置,application.yml文件的默认配置

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

注意:template-loader-path: classpath:/templates/freemarker中/templates/freemarke要和图5中的包一致。

  1. 设置ftl文件

Springboot模块(Freemarker模板和Thymeleaf模板)

Springboot模块(Freemarker模板和Thymeleaf模板)

Springboot模块(Freemarker模板和Thymeleaf模板)
Springboot模块(Freemarker模板和Thymeleaf模板)
或创一个html文件,修改后缀即可.ftl。

图5.

Springboot模块(Freemarker模板和Thymeleaf模板)

将下代码插入list.ftl

	<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.roleName}</td>
	        <td>${role.desc}</td>
	    </tr>
	    </#list>
	    </tbody>
	</table>
	
	<h2>include</h2>
	<#include 'foot.ftl'>
	
	<h2>局部变量(assign)/全局变量(global)</h2>
	 <#assign ctx1>
	     ${springMacroRequestContext.contextPath}
	 </#assign>
	
	<#global ctx2>
	    ${springMacroRequestContext.contextPath}
	</#global>
	
	${ctx1}和${ctx2}

在同级建一个foot.ftl,list.ftl加载foot.ftl.

  1. 新建一个Role 类和RoleController类

Role

	package com.zking.demo.entity;
	
	import lombok.Data;
	
	/**
	 * @author因果
	 * @site www.xiaomage.com
	 * @company xxx公司
	 * @create  2020-11-27 11:15
	 */
	@Data
	public class Role {
	
	    private Integer rid;
	    private String roleName;
	    private String desc;
	
	    public Role(Integer rid, String roleName, String desc) {
	        this.rid = rid;
	        this.roleName = roleName;
	        this.desc = desc;
	    }
	}

RoleController

@RequestMapping("/role/list")
    public ModelAndView roleList(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/list");

        mav.addObject("name",null);
        mav.addObject("sex","gay");
        List list = new ArrayList();
        list.add(new Role(1,"老师","教书育人"));
        list.add(new Role(2,"学生","知识改变命运"));
        mav.addObject("roles",list);

        return mav;
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

运行即可

效果图

Springboot模块(Freemarker模板和Thymeleaf模板)

当载端口后加项目名时

application.yaml

server:
  servlet:
    context-path: /ddd

Springboot模块(Freemarker模板和Thymeleaf模板)

总结:Freemarker模块和Thymelelaf,各有各的好处

本文地址:https://blog.csdn.net/yoonbongchi/article/details/110203334

相关标签: 笔记