当前位置:网站首页>Day_ 07 smart communication health project FreeMarker
Day_ 07 smart communication health project FreeMarker
2022-06-23 06:22:00 【fat ۣۖ tiger ۣۖ】
Smart health project The first 7 Chapter
1. Page static Introduction
In this chapter, we have realized the dynamic display of mobile terminal package list page and package details page . But we need to think about one thing , For these two pages , Every time users visit these two pages, they need to query the database to obtain dynamic data for display , And the traffic of these two pages is relatively large , This causes great access pressure to the database , And the frequency of data change in the database is not high . What methods do we need to use to reduce the pressure on the database and improve the performance of the system ? The answer is static pages .
Page static is actually the original dynamic web page ( For example, through ajax Request to dynamically obtain the data in the database and display the web page ) Change to a static web page generated by static technology , So when users visit the web page , The server responds directly to the user html page , Without the process of dynamically querying the database .
So these static HTML Do we need to write the page ourselves ? It doesn't need to be , We can use special page static technology to help us generate the required static HTML page , for example :Freemarker、thymeleaf etc. .
2. Freemarker Introduce
FreeMarker It's a use. Java Template engine written in language , It generates text output based on templates .FreeMarker And Web Container independent , That is to say Web Runtime , It doesn't know Servlet or HTTP. It can not only be used as the implementation technology of presentation layer , It can also be used to generate XML,JSP or Java etc. .

3. Freemarker Introductory cases
3.1 Environment building
establish maven Project and import Freemarker Of maven coordinate
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
3.2 Create template file
There are four elements in the template file :
1、 Text , The direct output part
2、 notes , namely <#–…–> The format will not output
3、 interpolation (Interpolation): namely ${…} part , Part of the data model will be used instead of the output
4、FTL Instructions :FreeMarker Instructions , and HTML The mark is similar to , Add... Before your name # To distinguish , No output
Freemarker The suffix of the template file can be arbitrary , The general suggestion is ftl.
stay D Disk creation ftl Catalog , stay ftl Create a directory with the name test.ftl Template file , The contents are as follows :
<html>
<head>
<meta charset="utf-8">
<title>Freemarker introduction </title>
</head>
<body>
<#-- I'm just a comment , I don't have any output -->
${name} Hello ,${message}
</body>
</html>
3.3 Generate the file
Use steps :
First step : Create a Configuration object , direct new An object . The parameter of the construction method is freemarker Version number of .
The second step : Set the path of the template file .
The third step : Set the character set used by the template file . It is commonly utf-8.
Step four : Load a template , Create a template object .
Step five : Create a dataset for the template to use , It can be pojo It can also be map. It's usually Map.
Step six : Create a Writer object , General creation FileWriter object , Specify the generated file name .
Step seven : Of the template object process Method output file .
Step eight : Closed flow .
public static void main(String[] args) throws Exception{
//1. Create configuration class
Configuration configuration=new Configuration(Configuration.getVersion());
//2. Set the directory where the template is located
configuration.setDirectoryForTemplateLoading(new File("D:\\ftl"));
//3. Set character set
configuration.setDefaultEncoding("utf-8");
//4. Load template
Template template = configuration.getTemplate("test.ftl");
//5. Creating a data model
Map map=new HashMap();
map.put("name", " Zhang San ");
map.put("message", " Welcome to the podcast !");
//6. establish Writer object
Writer out =new FileWriter(new File("d:\\test.html"));
//7. Output
template.process(map, out);
//8. close Writer object
out.close();
}
In the introductory case above Configuration The configuration object is created by yourself , The directory where the character set and template files are located is also in Java Specified in the code . When applied in a project, you can put Configuration The creation of objects is left to Spring Framework to complete , And inject the character set and the directory where the template is located through dependency injection .
4. Freemarker Instructions
4.1 assign Instructions
assign Instruction is used to define a variable on the page
(1) Define simple types
<#assign linkman=" Mr. zhou ">
Contacts :${linkman}
(2) Define object types
<#assign info={"mobile":"13812345678",'address':' Changping District, Beijing '} >
Telephone :${info.mobile} Address :${info.address}
4.2 include Instructions
include Directive is used to nest template files
(1) Create template file head.ftl
<h1> Black horse programmer </h1>
(2) Modify... In the introductory case test.ftl, stay test.ftl Use in template file include Instruction to import the above template file
<#include "head.ftl"/>
4.3 if Instructions
if Instruction for judgment
(1) Use... In template files if Command to judge
<#if success=true>
You have passed the real name certification
<#else>
You didn't pass real name Certification
</#if>
(2) stay java In the code is success Variable assignment
map.put("success", true);
stay freemarker In the judgment of , have access to = You can also use ==
4.4 list Instructions
list Instruction is used to traverse
(1) Use... In template files list Command to traverse
<#list goodsList as goods>
Name of commodity : ${goods.name} Price :${goods.price}<br>
</#list>
(2) stay java In the code is goodsList assignment
List goodsList=new ArrayList();
Map goods1=new HashMap();
goods1.put("name", " Apple ");
goods1.put("price", 5.8);
Map goods2=new HashMap();
goods2.put("name", " Banana ");
goods2.put("price", 2.5);
Map goods3=new HashMap();
goods3.put("name", " a mandarin orange ");
goods3.put("price", 3.2);
goodsList.add(goods1);
goodsList.add(goods2);
goodsList.add(goods3);
map.put("goodsList", goodsList);
5. Generate static pages of mobile terminal
We have learned before Freemarker The basic use method , Now we can put Freemarker Apply to a project , Help us generate the static page of mobile terminal package list and package details . Next, we need to think about a few questions :
(1) When is it appropriate to generate static pages ?
(2) Where will the static page be generated ?
(3) How many static pages should be generated ?
For the first question , It should be when the package data changes , Need to generate static pages , That is, we modify the package data through the background system ( Including new 、 Delete 、 edit ) when .
For the second question , If it is in the development stage, you can generate the file into the project , If you go online, you can generate files to the mobile terminal system tomcat in .
For the third question , The package list only needs one page , Display all the package list data on this page . The package details page needs to have multiple , That is, a package should correspond to a static page .
5.1 Environment building
stay health_common engineering pom Import in file Freemarker Of maven coordinate
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
5.2 Create template file
stay health_service_provider engineering WEB-INF Create... In the directory ftl Catalog , stay ftl Create template files in the directory mobile_setmeal.ftl and mobile_setmeal_detail.ftl file , The former is the template file used to generate the package list page , The latter is the template file for generating the package details page
(1)mobile_setmeal.ftl
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Above 3 individual meta label * must * Put it at the front , Anything else * must * followed by ! -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,user-scalable=no,minimal-ui">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../img/asset-favico.ico">
<title> make an appointment </title>
<link rel="stylesheet" href="../css/page-health-order.css" />
</head>
<body data-spy="scroll" data-target="#myNavbar" data-offset="150">
<div class="app" id="app">
<!-- Page header -->
<div class="top-header">
<span class="f-left"><i class="icon-back" onclick="history.go(-1)"></i></span>
<span class="center"> Wisdom and health </span>
<span class="f-right"><i class="icon-more"></i></span>
</div>
<!-- The page content -->
<div class="contentBox">
<div class="list-column1">
<ul class="list">
<#list setmealList as setmeal>
<li class="list-item">
<a class="link-page" href="setmeal_detail_${setmeal.id}.html">
<img class="img-object f-left" src="http://puco9aur6.bkt.clouddn.com/${setmeal.img}" alt="">
<div class="item-body">
<h4 class="ellipsis item-title">${setmeal.name}</h4>
<p class="ellipsis-more item-desc">${setmeal.remark}</p>
<p class="item-keywords">
<span>
<#if setmeal.sex == '0'>
There is no limit to sex
<#else>
<#if setmeal.sex == '1'>
male
<#else>
Woman
</#if>
</#if>
</span>
<span>${setmeal.age}</span>
</p>
</div>
</a>
</li>
</#list>
</ul>
</div>
</div>
</div>
<!-- page css js -->
<script src="../plugins/vue/vue.js"></script>
<script src="../plugins/vue/axios-0.18.0.js"></script>
</body>
Note that the hyperlinks corresponding to each package in the above template file are as follows :
<a class="link-page" href="setmeal_detail_${setmeal.id}.html">
You can see , The address of the link is dynamically constructed , If the package is id by 1, The corresponding hyperlink address is setmeal_detail_1.html; If the package is id by 5, The corresponding hyperlink address is setmeal_detail_5.html. So we need to generate a static page of package details for each package .
(2)mobile_setmeal_detail.ftl
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Above 3 individual meta label * must * Put it at the front , Anything else * must * followed by ! -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,user-scalable=no,minimal-ui">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../img/asset-favico.ico">
<title> Appointment details </title>
<link rel="stylesheet" href="../css/page-health-orderDetail.css" />
<script src="../plugins/vue/vue.js"></script>
<script src="../plugins/vue/axios-0.18.0.js"></script>
<script src="../plugins/healthmobile.js"></script>
</head>
<body data-spy="scroll" data-target="#myNavbar" data-offset="150">
<div id="app" class="app">
<!-- Page header -->
<div class="top-header">
<span class="f-left"><i class="icon-back" onclick="history.go(-1)"></i></span>
<span class="center"> Wisdom and health </span>
<span class="f-right"><i class="icon-more"></i></span>
</div>
<!-- The page content -->
<div class="contentBox">
<div class="card">
<div class="project-img">
<img src="http://puco9aur6.bkt.clouddn.com/${setmeal.img}" width="100%" height="100%" />
</div>
<div class="project-text">
<h4 class="tit">${setmeal.name}</h4>
<p class="subtit">${setmeal.remark}</p>
<p class="keywords">
<span>
<#if setmeal.sex == '0'>
There is no limit to sex
<#else>
<#if setmeal.sex == '1'>
male
<#else>
Woman
</#if>
</#if>
</span>
<span>${setmeal.age}</span>
</p>
</div>
</div>
<div class="table-listbox">
<div class="box-title">
<i class="icon-zhen"><span class="path1"></span><span class="path2"></span></i>
<span> Package details </span>
</div>
<div class="box-table">
<div class="table-title">
<div class="tit-item flex2"> Project name </div>
<div class="tit-item flex3"> Project content </div>
<div class="tit-item flex3"> Project interpretation </div>
</div>
<div class="table-content">
<ul class="table-list">
<#list setmeal.checkGroups as checkgroup>
<li class="table-item">
<div class="item flex2">${checkgroup.name}</div>
<div class="item flex3">
<#list checkgroup.checkItems as checkitem>
<label>
${checkitem.name}
</label>
</#list>
</div>
<div class="item flex3">${checkgroup.remark}</div>
</li>
</#list>
</ul>
</div>
<div class="box-button">
<a @click="toOrderInfo()" class="order-btn"> Make an appointment now </a>
</div>
</div>
</div>
</div>
</div>
<script> var vue = new Vue({
el:'#app', methods:{
toOrderInfo(){
window.location.href = "orderInfo.html?id=${setmeal.id}"; } } }); </script>
</body>
5.3 The configuration file
(1) stay health_service_provider Create a property file in the project freemarker.properties
out_put_path=D:/ideaProjects/health_parent/health_mobile/src/main/webapp/pages
Through the above configuration, you can specify that the static HTML Directory location of page generation
(2) stay health_service_provider engineering Spring Configuration in profile
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- Specify the directory where the template file is located -->
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<!-- Specify character set -->
<property name="defaultEncoding" value="UTF-8" />
</bean>
<context:property-placeholder location="classpath:freemarker.properties"/>
5.4 Generate static page
modify health_service_provider In the project SetmealServiceImpl Class add Method , Add logic to generate static pages .
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private SetmealDao setmealDao;
@Autowired
private JedisPool jedisPool;
@Value("${out_put_path}")// Read the path of the output directory from the properties file
private String outputpath ;
// New package , Also associated with inspection group
public void add(Setmeal setmeal, Integer[] checkgroupIds) {
setmealDao.add(setmeal);
Integer setmealId = setmeal.getId();// Get the package id
this.setSetmealAndCheckGroup(setmealId,checkgroupIds);
// After completing the database operation, you need to save the picture name to redis
jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
// After adding the package, you need to regenerate the static page
generateMobileStaticHtml();
}
// Generate static page
public void generateMobileStaticHtml() {
// Prepare the data required in the template file
List<Setmeal> setmealList = this.findAll();
// Generate static page of package list
generateMobileSetmealListHtml(setmealList);
// Generate static page of package details ( Multiple )
generateMobileSetmealDetailHtml(setmealList);
}
// Generate static page of package list
public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("setmealList", setmealList);
this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
}
// Generate static page of package details ( Multiple )
public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
for (Setmeal setmeal : setmealList) {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("setmeal", this.findById(setmeal.getId()));
this.generateHtml("mobile_setmeal_detail.ftl",
"setmeal_detail_"+setmeal.getId()+".html",
dataMap);
}
}
public void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Writer out = null;
try {
// Load template file
Template template = configuration.getTemplate(templateName);
// Generate the data
File docFile = new File(outputpath + "\\" + htmlPageName);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// The output file
template.process(dataMap, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
You can see through the above code , The name of the package list page we generated is m_setmeal.html, In order to be able to access this page on the mobile side , It is necessary to integrate... In the mobile terminal project /pages/index.html Modify the hyperlink address of the page :
<a href="/pages/m_setmeal.html" class="link-page">
<div class="type-title">
<h3> Appointment for physical examination </h3>
<p> Real time reservation </p>
</div>
<div class="type-icon">
<i class="icon-zhen">
<span class="path1"></span><span class="path2"></span>
</i>
</div>
</a>
边栏推荐
- Gplearn appears assignment destination is read only
- Add and multiply two polynomials using linked list
- Word pattern for leetcode topic analysis
- [focus on growth and build a dream for the future] - TDP year-end event, three chapters go to the Spring Festival!
- Day_05 传智健康项目-预约管理-预约设置
- [database backup] complete the backup of MySQL database through scheduled tasks
- Day_02 传智健康项目-预约管理-检查项管理
- 什么是PDCA循环?如何整合 PDCA 循环和 OKR
- Pyinstaller 打包pyttsx3 出错
- jvm-05. garbage collection
猜你喜欢

ant使用总结(二):相关命令说明

Redis sentry

Summary of ant usage (I): using ant to automatically package apk

(1) Basic learning - Common shortcut commands of vim editor

【Vivado那些事儿】XilinxCEDStore介绍

【Cocos2d-x】自定义环形菜单

Day_01 传智健康项目-项目概述和环境搭建

100-300 cases of single chip microcomputer program (detailed explanation of notes)

Day_06 传智健康项目-移动端开发-体检预约

ant使用总结(三):批量打包apk
随机推荐
(1) Basic learning - Common shortcut commands of vim editor
Wireshark TS | video app cannot play
SSM project construction
Day_10 传智健康项目-权限控制、图形报表
什么是PDCA循环?如何整合 PDCA 循环和 OKR
11、 Realization of textile fabric off shelf function
sklearn sklearn中的模型调参利器 gridSearchCV(网格搜索)
WordPress Core 5.8.2 - 'WP_ Query'SQL injection
[database backup] complete the backup of MySQL database through scheduled tasks
Leetcode topic resolution integer to Roman
【Leetcode】431. Encode N-ary Tree to Binary Tree(困难)
[cocos2d-x] screenshot sharing function
Find the number of nodes in the widest layer of a binary tree
Pat class B 1017 C language
Kotlin collaboration +retro most elegant network request use
Pat class B 1022 d-ary a+b
Design scheme of Small PLC based on t5l1
Day_03 传智健康项目-预约管理-检查组管理
Day_05 传智健康项目-预约管理-预约设置
jvm-06. Garbage collector