CMS系统学习(四)

一、模板技术

    • 1.freemarker:是比较流行的一个模板技术【ftl】
    1. 使用freemarker的步骤(以后只需要百度查找即可)
      1.导包(freemarker是一个小框架)
      2.创建一个配置对象Configuration(加个版本)
      3.设置加载路径
      4.设置字符集(默认)
      5.创建模板(准备一个ftl模板)
      6.准备数据(Map,对象)
      7.数据+模板=输出文件(Writer)
package cn.itsource.cms.freemarker;

import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerTest {

	/**
	 *  2.创建一个配置对象 (传递一个版本 )
		3.设置模板加载路径
		4设置一个模板编码
		5.获取一个模板对象
		6获取一个数据
		7生成文件
	 * @throws Exception
	 */
	@Test
	public void testMap() throws Exception {
		//1.创建一个配置对象 (传递一个版本 )
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		//2.设置模板的加载路径(就是找到模板的目标的路径)
		// Directory:目录  Template:模板  Loading:加载
		String path = "H:/eclipse-jee-neon-2-win32-x86_64/eclipse-workspace/cms/src/main/webapp/template";
		cfg.setDirectoryForTemplateLoading(new File(path));
		//3.设置模板的编码 UTF-8
		cfg.setDefaultEncoding("UTF-8");
		//4.获取一个模板对象
		Template template = cfg.getTemplate("my.ftl");
		//5.准备相应的数据(Map,对象)
		Map dataMap = new HashMap<>();
		dataMap.put("username", "飞天猪");
		dataMap.put("age", 45);
		dataMap.put("sex", false);
		
		List<MyUser> userList = Arrays.asList(
					new MyUser("游戏币",23),
					new MyUser("人民币",23),
					new MyUser("金币",23),
					new MyUser("QQ币",23)
				);
		//把集合放到map中去
		dataMap.put("userList", userList);
		
		
		//6.生成文件
		//数据(dataMap)+模板(template) = 输出文件(out)
		File newFile = new File(path,"mytest.html");
		FileWriter out = new FileWriter(newFile);
		template.process(dataMap, out);
		out.flush();
	}

	
	@Test
	public void testMap02() throws Exception {
		//1.创建一个配置对象 (传递一个版本 )
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		//2.设置模板的加载路径(就是找到模板的目标的路径)
		// Directory:目录  Template:模板  Loading:加载
		String path = "H:/eclipse-jee-neon-2-win32-x86_64/eclipse-workspace/cms/src/main/webapp/template";
		cfg.setDirectoryForTemplateLoading(new File(path));
		//3.设置模板的编码 UTF-8
		cfg.setDefaultEncoding("UTF-8");
		//4.获取一个模板对象
		Template template = cfg.getTemplate("my2.ftl");
		//5.准备相应的数据(Map,对象)
		Map dataMap = new HashMap<>();
		//  准备数据map
		Map userMap = new HashMap<>();
		userMap.put("username", "飞天猪");
		userMap.put("age", 45);
		userMap.put("sex", "男");
		
		dataMap.put("userMap", userMap);
		
		//6.生成文件
		//数据(dataMap)+模板(template) = 输出文件(out)
		File newFile = new File(path,"mytest2.html");
		FileWriter out = new FileWriter(newFile);
		template.process(dataMap, out);
		out.flush();
	}

	@Test
	public void testObj() throws Exception {
		//1.创建一个配置对象(给它一个版本)
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		//2.设置模板的路径的加载
		String path = "H:/eclipse-jee-neon-2-win32-x86_64/eclipse-workspace/cms/src/main/webapp/template";
		cfg.setDirectoryForTemplateLoading(new File(path));
		//3.设置默认编码
		cfg.setDefaultEncoding("UTF-8");
		//4.获取模板
		Template template = cfg.getTemplate("my.ftl");
		//5.准备数据
		MyUser user = new MyUser();
		user.setUsername("跑地猪");
		user.setAge(12);
		//6.把数据,模板进行输出
		File file = new File(path,"mytest2.html");
		FileWriter out = new FileWriter(file);
		template.process(user, out);
		out.flush();
	}
	
	
}






模板:my.ftl

<html>
<head>
	<meta charset="UTF-8">
	<title>我是一个测试</title>
</head>
<body>
	${username}, 你好啊!!! ============ ${age} ======
	<#if sex>
	 	男
	 	<#else>
	 	女
	</#if>
	
	<#list userList as user>
		${user.username},${user.age}
	</#list>
	
</body>
</html>

模板:my2.ftl

<html>
<head>
	<meta charset="UTF-8">
	<title>我是一个测试</title>
</head>
<body>
	
	Map是否可以循环???
	<#list userMap?keys as key>
		${key} ==== ${userMap[key]}
	</#list>	
</body>
</html>

3.案例一:代码生成器(半成品)

package cn.itsource.cms.freemarker;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import freemarker.template.Configuration;
import freemarker.template.Template;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class CreateDomainTest {

	@Autowired
	private DataSource dataSource;
	
	String tableName = "t_user";
	String className = "User";
	@Test
	public void testCreate() throws Exception {
		//1.拿到连接对象
		Connection connection = dataSource.getConnection();
		//2.确定找的是哪一张表
		PreparedStatement ps = connection.prepareStatement("select * from "+tableName);
		//3.拿到结果集
		ResultSet rs = ps.executeQuery();
		//3.拿到参数的原数据
		ResultSetMetaData metaData = rs.getMetaData();
		//4.拿到当前表有多少个字段
		int count = metaData.getColumnCount();
		//5.遍历(循环)相应的字段
		// 准备list,里面会装咱们的所有字段
		List<Map> list = new ArrayList<>(); 
		for(int i=1;i<=count;i++){
			//System.out.println(metaData.getColumnTypeName(i));
			String type = metaData.getColumnClassName(i).replaceFirst("java.lang.", "");
			String name =metaData.getColumnName(i);
			//把name的第一个首字母变成大写的字母 Name
			String upperName = name.substring(0, 1).toUpperCase() + name.substring(1);
			Map<String,Object> map = new HashMap<>();
			map.put("type", type);
			map.put("name", name);
			map.put("upperName", upperName);
			list.add(map);
		}
		
		//准备好模板技术的代码
		//1.创建一个配置对象 (传递一个版本 )
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		//2.设置模板的加载路径(就是找到模板的目标的路径)
		// Directory:目录  Template:模板  Loading:加载
		String path = "H:/eclipse-jee-neon-2-win32-x86_64/eclipse-workspace/cms/src/main/webapp/template";
		cfg.setDirectoryForTemplateLoading(new File(path));
		//3.设置模板的编码 UTF-8
		cfg.setDefaultEncoding("UTF-8");
		//4.获取一个模板对象
		Template template = cfg.getTemplate("domain.java");
		//5.准备相应的数据(Map,对象)
		Map dataMap = new HashMap<>();
		dataMap.put("className", className);
		dataMap.put("filedList", list);
		
		//6.生成文件
		//数据(dataMap)+模板(template) = 输出文件(out)
		File newFile = new File(path,className+".java");
		FileWriter out = new FileWriter(newFile);
		template.process(dataMap, out);
		out.flush();
		
	}
	
	
	
}

模板:domain.java

package cn.itsource.cms.domain;

public class ${className} {
	
	<#list filedList as filed>
	private ${filed.type} ${filed.name} ;
	</#list>
	
	
	<#list filedList as filed>
	public ${filed.type} get${filed.upperName}() {
		return ${filed.name};
	}
	public void set${filed.upperName}(${filed.type} ${filed.name}) {
		this.${filed.name} = ${filed.name};
	}
	</#list>
	
}

4.案例二:动态网页静态化(添加,修改)

	修改的时候需要把原生的那个静态化页面删除
	删除数据的时候也要把静态化页面删除
	需要把路径记录下来,才可能去找到这个静态化页面
//添加或者修改的跳转
	@RequestMapping("/save")
	public String save(Jobs jobs,HttpServletRequest req) throws Exception{
		//如果这个页面已经存在,那么我们就要把它给干掉(删除)
		String realPath = req.getServletContext().getRealPath("/statichtml");
		String htmlUrl = jobs.getHtmlurl();
		if(htmlUrl!=null){
			File jobFile = new File(realPath,htmlUrl);
			// 判断这个文件是否存在
			if(jobFile.exists()){
				System.gc(); //垃圾回收
				jobFile.delete();
			}
		}
		//1.拿到配置对象
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		//2.加载路径
		cfg.setDirectoryForTemplateLoading(new File(realPath));
		//3.设置字符编码
		cfg.setDefaultEncoding("UTF-8");
		//4.获取模板
		Template template = cfg.getTemplate("details.ftl");
		//5.准备数据(数据就是jobs)
		Map dataMap = new HashMap<>();
		dataMap.put("job", jobs);
		//6.输出数据
		//  6.1 准备一个html的名称(要保证唯一性)
		String uuidHtml = UUID.randomUUID().toString() +".html";
		File file = new File(realPath,uuidHtml);
		FileWriter out = new FileWriter(file);
		// 6.2 把数据+模板=输出
		template.process(dataMap, out);
		out.flush();
		out.close();
		
		//把相应的名称放到jobs中去
		jobs.setHtmlurl(uuidHtml);
		if(jobs.getId()!=null){
			jobsService.update(jobs);
		}else{
			jobsService.save(jobs);
		}
		return "redirect:/jobs/query";
	}
	
	//添加或者修改的跳转
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable("id") Integer id,HttpServletRequest req){
		//拿到相应的地址
		String realPath = req.getServletContext().getRealPath("/statichtml");
		Jobs jobs = jobsService.findOne(id);
		String htmlUrl = jobs.getHtmlurl();
		//创建相应的文件
		File file = new File(realPath,htmlUrl);
		if(file.exists()){
			System.gc();
			file.delete();
		}
		
		jobsService.delete(id);
		return "redirect:/jobs/query";
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值