thymeleaf模板引擎(青橙前台day01)

2024-05-02 01:38

本文主要是介绍thymeleaf模板引擎(青橙前台day01),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

①. thymeleaf简介

1>. thymeleaf简介

1.什么是thymeleaf

  • Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎。SpringBoot 官网推荐使用的模板引擎是thymeleaf

在这里插入图片描述

2. thymeleaf PK Vue.js

    vue.js 是前端渲染,异步请求(页面先打开,再看到数据),不会被搜索引擎抓取[管理后台]thymeleaf 后端渲染,比jsp还强大,支持搜索

3. thymeleaf快速入门

  • ①.导包
	<dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf</artifactId><version>3.0.11.RELEASE</version></dependency>
  • ②. 在resource下创建一个test.html
	<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body><span th:text="${name}"></span></body></html>
  • ③. 创建测试类,编写代码
package com.itcast.demo;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;public class Test {public static void main(String[] args) {// 1.上下文Context context = new Context();//创建数据模型Map<String, Object> dataModel =new HashMap();dataModel.put("name","青橙电商系统");context.setVariables(dataModel);// 2.准备文件File dest = new File("d:/test_out.html");// 3.生成页面try {PrintWriter writer = new PrintWriter(dest, "UTF-8");ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();//模板解析器resolver.setTemplateMode(TemplateMode.HTML);//模板模型resolver.setSuffix(".html");//后缀TemplateEngine engine = new TemplateEngine();//创建模板引擎engine.setTemplateResolver(resolver);//设置模板解析器engine.process("test", context, writer);//执行模板引擎} catch (Exception e) {e.printStackTrace();}}
}

4. thymeleaf标签实战

  • ①. thymeleaf标签

在这里插入图片描述

  • ②. 实战
    在这里插入图片描述

②. 首页广告轮播图渲染

2>. 首页广告轮播图渲染

1.需求分析

  • 使用Thymeleaf实现首页广告轮播图的渲染
    在这里插入图片描述

2.表结构分析

在这里插入图片描述

3. 搭建网站前台工程(thymeleaf整合springBoot)

  • ①. 新建qingcheng_web_portal工程,此工程为网站前台工程,pom.xml参照 qingcheng_web_manager工程,另外再添加thymeleaf-spring5依赖
        <dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId><version>3.0.11.RELEASE</version></dependency>
  • ②. qingcheng_web_portal工程新建web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"version="2.5"><!-- 解决post乱码 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:applicationContext*.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><welcome-file-list><welcome-file>/index.do</welcome-file></welcome-file-list></web-app>
  • ③. resources下新建配置文件applicationContext- thymeleaf.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--spring整合的资源模板解析器--><bean id="templateResolver"class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"><!--模板前缀   目录--><property name="prefix" value="/WEB-INF/templates/"/><!--模板后缀  扩展名--><property name="suffix" value=".html"/><!--字符集--><property name="characterEncoding" value="UTF-8"/><!--模式  html5--><property name="templateMode" value="HTML5"/></bean><!--模板引擎--><bean id="templateEngine"class="org.thymeleaf.spring5.SpringTemplateEngine"><property name="templateResolver" ref="templateResolver"/></bean><!--模板视图解析器--><bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"><property name="templateEngine" ref="templateEngine"/><property name="characterEncoding" value="UTF-8"/></bean></beans>
  • ④. webapp/WEB-INF下创建templates文件夹用于存放模板文件

4. 具体代码实现

  • ①. service 和 controller代码实现
@Controller
public class IndexController {@Referenceprivate AdService adService;@Referenceprivate CategoryService categoryService;@RequestMapping("/index")public String index(Model model){/*1.轮播图*/List<Ad> lbList = adService.findByPosition("index_lb");model.addAttribute("lbt",lbList);/*2.首页分类导航渲染*/List<Map> categoryList = categoryService.findCategoryTree();model.addAttribute("categoryList",categoryList);return "index";}
}
    //根据广告位置查询广告列表public List<Ad> findByPosition(String position) {//创建查询条件Example example=new Example(Ad.class);Example.Criteria criteria = example.createCriteria();criteria.andEqualTo("position",position);criteria.andLessThanOrEqualTo("startTime",new Date());criteria.andGreaterThanOrEqualTo("endTime",new Date());criteria.andEqualTo("status","1");return adMapper.selectByExample(example);}
  • ②. 使用thymeleaf怎么实现的
    在这里插入图片描述

③. 首页分类导航渲染

3>. 首页分类导航渲染

   首页分类导航的渲染: 拿到数据后,在模板页面中进行三次循环即可[注意:这里前端要一个树状的结构,我们需要一个parentId的字段]思路有两种:1.通过parentId=0 查询得到一级菜单,遍历一级菜单,得到二级菜单,遍历二级菜单,
得到三级菜单,不推荐使用,因为和数据库需要频繁的交互,交互次数=1+一级菜单数量+二级菜单数量2.首先把符合条件的记录(每一级菜单列表)[推荐使用]
    //首页分类导航渲染public List<Map> findCategoryTree() {Example example=new Example(Category.class);Example.Criteria criteria = example.createCriteria();criteria.andEqualTo("isShow","1");//显示example.setOrderByClause("seq");//排序List<Category> categories = categoryMapper.selectByExample(example);return findByParentId(categories,0);}public List<Map> findByParentId(List<Category>categories,Integer parentId){List<Map>listMap=new ArrayList<Map>();for(Category category:categories){if(category.getParentId().equals(parentId)){Map map=new HashMap();map.put("name",category.getName());map.put("menus",findByParentId(categories,category.getId()));listMap.add(map);}}return listMap;}

④. 商品详细页静态渲染

4>. 商品详细页静态渲染

  • ①. 为什么使用静态渲染而不用动态渲染?

在这里插入图片描述

  • ②. 核心代码实现[主要掌握配置静态化的过程]
@RestController
@RequestMapping("/item")
public class ItemController {@Referenceprivate SpuService spuService;@Referenceprivate CategoryService categoryService;@Value("${pagePath}")private String pagePath;@Autowiredprivate TemplateEngine templateEngine;@GetMapping("/createPage")public void createPage(String spuId){//1.查询商品信息Goods goods = spuService.findGoodsById(spuId);// 获取spu信息Spu spu = goods.getSpu();// 获取sku列表List<Sku> skuList = goods.getSkuList();//查询商品分类List<String> categoryList=new ArrayList<>();categoryList.add(  categoryService.findById(spu.getCategory1Id()).getName() );//一级分类categoryList.add(  categoryService.findById(spu.getCategory2Id()).getName() );//二级分类categoryList.add(  categoryService.findById(spu.getCategory3Id()).getName() );//三级分类//sku地址列表Map<String,String> urlMap=new HashMap<>();for(Sku sku:skuList){if("1".equals(sku.getStatus())){String specJson = JSON.toJSONString( JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);urlMap.put(specJson,sku.getId()+".html");}}//2.批量生成sku页面for(Sku sku:skuList){//(1) 创建上下文和数据模型Context context=new Context();Map<String,Object> dataModel= new HashMap<>();dataModel.put("spu",spu);dataModel.put("sku",sku);dataModel.put("categoryList",categoryList);dataModel.put("skuImages", sku.getImages().split(",") );//sku图片列表dataModel.put("spuImages", spu.getImages().split(",") );//spu图片列表Map paraItems=   JSON.parseObject( spu.getParaItems());//参数列表dataModel.put("paraItems",paraItems);Map<String,String> specItems = (Map)JSON.parseObject(sku.getSpec());//规格列表  当前skudataModel.put("specItems",specItems);//{"颜色":["天空之境","珠光贝母"],"内存":["8GB+64GB","8GB+128GB","8GB+256GB"]}//{"颜色":[{ 'option':'天空之境',checked:true },{ 'option':'珠光贝母',checked:false }],.....}Map<String,List> specMap =  (Map)JSON.parseObject(spu.getSpecItems());//规格和规格选项for(String key :specMap.keySet()  ){  //循环规格List<String> list = specMap.get(key);//["天空之境","珠光贝母"]List<Map> mapList=new ArrayList<>();//新的集合  //[{ 'option':'天空之境',checked:true },{ 'option':'珠光贝母',checked:false }]//循环规格选项for(String value:list){Map map=new HashMap();map.put("option",value);//规格选项if(specItems.get(key).equals(value) ){  // 如果和当前sku的规格相同,就是选中map.put("checked",true);//是否选中}else{map.put("checked",false);//是否选中}Map<String,String>  spec= (Map)JSON.parseObject(sku.getSpec()) ;//当前的Skuspec.put(key,value);String specJson = JSON.toJSONString(spec , SerializerFeature.MapSortField);map.put("url",urlMap.get(specJson));mapList.add(map);}specMap.put(key,mapList);//用新的集合替换原有的集合}dataModel.put("specMap" ,specMap);context.setVariables(dataModel);//(2)准备文件File dir =new File(pagePath);if( !dir.exists()){dir.mkdirs();}File dest= new File(dir, sku.getId()+".html" );//(3)生成页面try {PrintWriter writer=new PrintWriter( dest,"UTF-8");templateEngine.process("item",context,writer );System.out.println("生成页面:"+sku.getId()+".html");} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}}}

这篇关于thymeleaf模板引擎(青橙前台day01)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/953136

相关文章

MySQL之InnoDB存储引擎中的索引用法及说明

《MySQL之InnoDB存储引擎中的索引用法及说明》:本文主要介绍MySQL之InnoDB存储引擎中的索引用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1、背景2、准备3、正篇【1】存储用户记录的数据页【2】存储目录项记录的数据页【3】聚簇索引【4】二

SpringBoot集成LiteFlow工作流引擎的完整指南

《SpringBoot集成LiteFlow工作流引擎的完整指南》LiteFlow作为一款国产轻量级规则引擎/流程引擎,以其零学习成本、高可扩展性和极致性能成为微服务架构下的理想选择,本文将详细讲解Sp... 目录一、LiteFlow核心优势二、SpringBoot集成实战三、高级特性应用1. 异步并行执行2

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

MySQL 存储引擎 MyISAM详解(最新推荐)

《MySQL存储引擎MyISAM详解(最新推荐)》使用MyISAM存储引擎的表占用空间很小,但是由于使用表级锁定,所以限制了读/写操作的性能,通常用于中小型的Web应用和数据仓库配置中的只读或主要... 目录mysql 5.5 之前默认的存储引擎️‍一、MyISAM 存储引擎的特性️‍二、MyISAM 的主

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>

Python中Flask模板的使用与高级技巧详解

《Python中Flask模板的使用与高级技巧详解》在Web开发中,直接将HTML代码写在Python文件中会导致诸多问题,Flask内置了Jinja2模板引擎,完美解决了这些问题,下面我们就来看看F... 目录一、模板渲染基础1.1 为什么需要模板引擎1.2 第一个模板渲染示例1.3 模板渲染原理二、模板

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环