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

相关文章

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

轻量级在线服装3D定制引擎Myway简介

我写的面向web元宇宙轻量级系列引擎中的另外一个,在线3D定制引擎Myway 3D。 用于在线商品定制,比如个性化服装的定制、日常用品(如杯子)、家装(被套)等物品的在线定制。 特性列表: 可更换衣服款式,按需定制更换模型可实时更改材质颜色可实时添加文本,并可实时修改大小、颜色和角度,支持自定义字体可实时添加艺术图标,并可实时修改大小、颜色和角度,支持翻转、各种对齐可更改衣服图案,按需求定制

亮相WOT全球技术创新大会,揭秘火山引擎边缘容器技术在泛CDN场景的应用与实践

2024年6月21日-22日,51CTO“WOT全球技术创新大会2024”在北京举办。火山引擎边缘计算架构师李志明受邀参与,以“边缘容器技术在泛CDN场景的应用和实践”为主题,与多位行业资深专家,共同探讨泛CDN行业技术架构以及云原生与边缘计算的发展和展望。 火山引擎边缘计算架构师李志明表示:为更好地解决传统泛CDN类业务运行中的问题,火山引擎边缘容器团队参考行业做法,结合实践经验,打造火山

React+TS前台项目实战(十七)-- 全局常用组件Dropdown封装

文章目录 前言Dropdown组件1. 功能分析2. 代码+详细注释3. 使用方式4. 效果展示 总结 前言 今天这篇主要讲全局Dropdown组件封装,可根据UI设计师要求自定义修改。 Dropdown组件 1. 功能分析 (1)通过position属性,可以控制下拉选项的位置 (2)通过传入width属性, 可以自定义下拉选项的宽度 (3)通过传入classN

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共

C++标准模板库STL介绍

STL的六大组成部分 STL(Standard Template Library)是 C++ 标准库中的一个重要组成部分,提供了丰富的通用数据结构和算法,使得 C++ 编程变得更加高效和方便。STL 包括了 6 大类组件,分别是算法(Algorithm)、容器(Container)、空间分配器(Allocator)、迭代器(Iterator)、函数对象(Functor)、适配器(Adapter)

HTML5文旅文化旅游网站模板源码

文章目录 1.设计来源文旅宣传1.1 登录界面演示1.2 注册界面演示1.3 首页界面演示1.4 文旅之行界面演示1.5 文旅之行文章内容界面演示1.6 关于我们界面演示1.7 文旅博客界面演示1.8 文旅博客文章内容界面演示1.9 联系我们界面演示 2.效果和源码2.1 动态效果2.2 源代码2.3 源码目录 源码下载万套模板,程序开发,在线开发,在线沟通 作者:xcLeigh

静态文件及模板

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm=1001.2014.3001.5501 1  静态文件 动态Web应用也会需要静态文件,通常是CSS和JavaScript文件。Flask可以向已经配置好的Web服务器提供静态文件,只要在包或模块所在的目录中创建一个名为s

周末设计高端企业_集团官网主题Discuz模板

风格名称: 周末设计_高端企业_集团官网 适用版本: Discuz! X3.0、X3.1、X3.2、X3.3、F1.0 风格编码: 使用语言包结构,适合全部编码 周末设计高端企业_集团官网主题Discuz模板

游戏高度可配置化(一)通用数据引擎(data-e)及其在模块化游戏开发中的应用构想图解

游戏高度可配置化(一)通用数据引擎(data-e)及其在模块化游戏开发中的应用构想图解 码客 卢益贵 ygluu 关键词:游戏策划 可配置化 模块化配置 数据引擎 条件系统 红点系统 一、前言 在插件式模块化软件开发当中,既要模块高度独立(解耦)又要共享模块数据,最好的方法是有个中间平台(中间件)提供标准的接口来进行数据的交换,这在很多行业软件开发中已经广泛应用。但是,由于中间件的抽象和封