freemarker静态化生成html页面乱码的问题
今天在整理之前所学的知识,在复习freemarker生成html页面的时候出现了中文乱码的问题,
在费了一番时间后终于找到问题的原因,觉得挺有意思,就把这段记录下来。
下面是springmvc的核心代码
<!-- freemarker的配置 --> <bean id="freemarkerconfigurer" class="org.springframework.web.servlet.view.freemarker.freemarkerconfigurer"> <!-- templateloaderpath :前缀 --> <property name="templateloaderpath" value="/web-inf/ftl/"></property> <!-- 编码 --> <property name="defaultencoding" value="utf-8"></property> <!-- 可选的配置 --> <property name="freemarkersettings"> <props> <prop key="template_update_delay">10</prop> <prop key="locale">zh_cn</prop> <prop key="datetime_format">yyyy-mm-dd hh:mm:ss</prop> <prop key="date_format">yyyy-mm-dd</prop> <prop key="time_format">hh:mm:ss</prop> <!-- 页面数值的显示格式 --> <prop key="number_format">#.##</prop><!-- 88,282,882,888,888 --><!-- 88282882888888.00 --> </props> </property> </bean> <!-- freemarker的解析器 --> <bean id="freemarkerviewresolver" class="org.springframework.web.servlet.view.freemarker.freemarkerviewresolver"> <!-- 后缀 .ftl:是freemarker模板文件的后缀 --> <property name="suffix" value=".ftl"></property> <property name="contenttype" value="text/html;charset=utf-8"></property> <!-- 方便页面获得项目的绝对路径 --> <property name="requestcontextattribute" value="request"></property> </bean>
然后是controller的核心代码
@requestmapping("/gethtml") public string gethtml(httpservletrequest request,httpservletresponse response) throws exception{ //第一步 freemarkerconfigurer得到一个configure对象 configuration configuration = freemarkerconfigurer.getconfiguration(); //第二步 得到一个模版文件 template template = configuration.gettemplate("index.ftl"); //第三步 构建数据模型 map<string, object> map = new hashmap<string, object>(); map.put("uname", "zhangsan"); map.put("booklist", bookdaoimpl.getbooklist()); system.out.println(bookdaoimpl.getbooklist().get(0).getauthor()); //第四步 指定一个文件夹 构建一个输出流 string dir = request.getsession().getservletcontext().getrealpath("/web-inf/"); //printwriter printwriter = new printwriter(new filewriter(new file(dir,"index.html"))); system.out.println(dir); //第五步 数据模型+模版文件 = 输出(控制台输出,html文件) template.process(map, printwriter); printwriter.flush(); return "success"; }
最后页面提示成功生成html页面
但在进入生成的html页面时发生了乱码
在网上也查了下大致给了以下几种解决方案
首先是说ftl文件的head上加上
<meta http-equiv="content-type" content="text/html; charset=utf-8">
因为我在springmvc的视图解析器配置了
<property name="contenttype" value="text/html;charset=utf-8"></property>
所以这个选择首先pass掉,然后说是在controller里加上
configuration.setdefaultencoding("utf-8");
不过因为我在freemarker的环境配置我也配置了默认的编码
<!-- 编码 --> <property name="defaultencoding" value="utf-8"></property>
所以应该也不是这个原因,后来我找到生成的html文件,发现用浏览器查看源代码虽然会乱码,但用记事本打开的时候所显示并没有乱码,然后判断是输出流的问题,通过网上查找发现filewriter和filereader使用的是系统默认的编码方式,因为filewriter本身不具有用户指定编码的方式,这里选择使用filewriter 的父类outputstreamwriter来读写操作,把代码
string dir = request.getsession().getservletcontext().getrealpath("/web-inf/"); //printwriter printwriter = new printwriter(new filewriter(new file(dir,"index.html")));
替换成
string dir = request.getsession().getservletcontext().getrealpath("/web-inf/index.html"); outputstreamwriter writer = new outputstreamwriter(new fileoutputstream(dir), "utf-8"); printwriter printwriter = new printwriter(writer);
后启动程序
乱码解决了,很开心!
freemarker页面静态化步骤以及相关注意事项
freemarker
导入坐标
<dependency> <groupid>org.freemarker</groupid> <artifactid>freemarker</artifactid> <version>2.3.23</version> </dependency>
创建模板文件
<html> <head> <meta charset="utf-8"> <title>freemarker入门</title> </head> <body> <#--我只是一个注释,我不会有任何输出 --> ${name}你好,${message} </body> </html>
生成文件
public static void main(string[] args) throws exception{ //1.创建配置类 configuration configuration=new configuration(configuration.getversion()); //2.设置模板所在的目录 configuration.setdirectoryfortemplateloading(new file("d:\\ftl")); //3.设置字符集,读取文件的编码 configuration.setdefaultencoding("utf-8"); //4.加载模板 template template = configuration.gettemplate("test.ftl"); //5.创建数据模型 map map=new hashmap(); map.put("name", "张三"); map.put("message", "欢迎来到中国!"); //6.创建writer对象 // // 指定输出编码格式 utf-8 writer writer = new bufferedwriter(new outputstreamwriter(new fileoutputstream ("d:\\ftl\\test.html"),"utf-8")); //writer out =new filewriter(new file("d:\\test.flt")); //7.输出 template.process(map, out); //8.关闭writer对象 out.close(); }
例子
分析
前面我们已经学习了freemarker的基本使用方法,下面我们就可以将freemarker应用到项目中,帮我们生成移动端套餐列表静态页面和套餐详情静态页面。
接下来我们需要思考几个问题:
(0)那些页面应该静态化? 数据不经常发生变化,访问量大的
(1)什么时候生成静态页面比较合适呢?
(2)将静态页面生成到什么位置呢?
(3)应该生成几个静态页面呢?
- 对于第一个问题,应该是当套餐数据发生改变时,需要生成静态页面,即我们通过后台系统修改套餐数据(包括新增、删除、编辑)时。
- 对于第二个问题,如果是在开发阶段可以将文件生成到项目工程中,如果上线后可以将文件生成到移动端系统运行的tomcat中。
- 对于第三个问题,套餐列表只需要一个页面就可以了,在这个页面中展示所有的套餐列表数据即可。套餐详情页面需要有多个,即一个套餐应该对应一个静态页面。
模板
mobile_setmeal.ftl
<!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <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" rel="external nofollow" rel="external nofollow" > <title>预约</title> <link rel="stylesheet" href="../css/page-health-order.css" rel="external nofollow" /> </head> <body data-spy="scroll" data-target="#mynavbar" data-offset="150"> <div class="app" id="app"> <!-- 页面头部 --> <div class="top-header"> <span class="f-left"><i class="icon-back" onclick="history.go(-1)"></i></span> <span class="center">大鹅健康</span> <span class="f-right"><i class="icon-more"></i></span> </div> <!-- 页面内容 --> <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" rel="external nofollow" > <img class="img-object f-left" src="http://py25jppgz.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'> 性别不限 <#else> <#if setmeal.sex == '1'> 男 <#else> 女 </#if> </#if> </span> <span>${setmeal.age}</span> </p> </div> </a> </li> </#list> </ul> </div> </div> </div> <!-- 页面 css js --> <script src="../plugins/vue/vue.js"></script> <script src="../plugins/vue/axios-0.18.0.js"></script> </body>
模板
<!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <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" rel="external nofollow" rel="external nofollow" > <title>预约详情</title> <link rel="stylesheet" href="../css/page-health-orderdetail.css" rel="external nofollow" /> <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"> <!-- 页面头部 --> <div class="top-header"> <span class="f-left"><i class="icon-back" onclick="history.go(-1)"></i></span> <span class="center">大鹅健康</span> <span class="f-right"><i class="icon-more"></i></span> </div> <!-- 页面内容 --> <div class="contentbox"> <div class="card"> <div class="project-img"> <img src="http://py25jppgz.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'> 性别不限 <#else> <#if setmeal.sex == '1'> 男 <#else> 女 </#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>套餐详情</span> </div> <div class="box-table"> <div class="table-title"> <div class="tit-item flex2">项目名称</div> <div class="tit-item flex3">项目内容</div> <div class="tit-item flex3">项目解读</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">立即预约</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>
配置文件
(1)在health_service_provider工程中创建属性文件freemarker.properties 通过上面的配置可以指定将静态html页面生成的目录位置
out_put_path=静态页面生成的位置
在spring的中进行配置
<bean id="freemarkerconfig" class="org.springframework.web.servlet.view.freemarker.freemarkerconfigurer"> <!--指定模板文件所在目录--> <property name="templateloaderpath" value="/web-inf/ftl/" /> <!--指定字符集--> <property name="defaultencoding" value="utf-8" /> </bean> <context:property-placeholder location="classpath:freemarker.properties"/>
13 java 代码
@autowired private setmealdao setmealdao; @autowired private jedispool jedispool; @autowired private checkgroupdao checkgroupdao; @autowired private checkitemdao checkitemdao; @autowired private freemarkerconfigurer freemarkerconfigurer; @value("${out_put_path}") private string outputpath;//从属性文件中读取要生成的html对应的目录 //新增套餐,同时关联检查组 public void add(setmeal setmeal, integer[] checkgroupids) { setmealdao.add(setmeal); integer setmealid = setmeal.getid();//获取套餐id this.setsetmealandcheckgroup(setmealid,checkgroupids); //完成数据库操作后需要将图片名称保存到redis jedispool.getresource().sadd(redisconstant.setmeal_pic_db_resources,setmeal.getimg()); //当添加套餐后需要重新生成静态页面(套餐列表页面、套餐详情页面) generatemobilestatichtml(); } //生成当前方法所需的静态页面 public void generatemobilestatichtml(){ //在生成静态页面之前需要查询数据 list<setmeal> list = setmealdao.findall(); //需要生成套餐列表静态页面 generatemobilesetmeallisthtml(list); //需要生成套餐详情静态页面 generatemobilesetmealdetailhtml(list); } //生成套餐列表静态页面 public void generatemobilesetmeallisthtml(list<setmeal> list){ map map = new hashmap(); //为模板提供数据,用于生成静态页面 map.put("setmeallist",list); genertehtml("mobile_setmeal.ftl","m_setmeal.html",map); } //生成套餐详情静态页面(可能有多个) public void generatemobilesetmealdetailhtml(list<setmeal> list){ for (setmeal setmeal : list) { map map = new hashmap(); map.put("setmeal",setmealdao.findbyid4detail(setmeal.getid())); genertehtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getid() + ".html",map); } } //通用的方法,用于生成静态页面 public void genertehtml(string templatename,string htmlpagename,map map){ configuration configuration = freemarkerconfigurer.getconfiguration();//获得配置对象 writer out = null; try { template template = configuration.gettemplate(templatename); //构造输出流 // 中文乱码 //out = new bufferedwriter (new outputstreamwriter (new fileoutputstream (outputpath + "/" + htmlpagename),"utf-8")); //构造输出流 out = new filewriter(new file(outputpath + "/" + htmlpagename)); //输出文件 template.process(map,out); out.close(); } catch (exception e) { e.printstacktrace(); } }
生成静态页面的通用方法
//通用的方法,用于生成静态页面(参数:templatename:模板,htmlpagename:生成的文件名称,map:数据) public void genertehtml(string templatename,string htmlpagename,map map){ configuration configuration = freemarkerconfigurer.getconfiguration();//获得配置对象 writer out = null; try { template template = configuration.gettemplate(templatename); //构造输出流 // 中文乱码 //out = new bufferedwriter (new outputstreamwriter (new fileoutputstream (outputpath + "/" + htmlpagename),"utf-8")); //构造输出流 out = new filewriter(new file(outputpath + "/" + htmlpagename)); //输出文件 template.process(map,out); out.close(); } catch (exception e) { e.printstacktrace(); } }
14 -测试
public void genbyid(integer setmealid){ map map = new hashmap(); map.put("setmeal",setmealdao.findbyid4detail(setmealid)); genertehtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmealid + ".html",map); }
总结
1导入写好的模板文件(放置到服务的提供方的web-inf下创建的ftl文件夹中)
2配置freemarker的静态页面生成的地方,在spring的配置文件中配置freemarker的相关bean的配置.
3判断在什么情况下生成静态页面比较合适,一般为数据改变的是时候生成(例如:信息的增加,修改,删除)并修改相关的实现方法.
4.运行程序,增加,修改,删除信息,调用静态化方法进行页面生成.(基本流程:增加,修改,删除信息–>查询数据库获取到相应的数据–>调用生成静态页面的通用方法进行页面的生成).
以上为个人经验,希望能给大家一个参考,也希望大家多多支持七九推。
发表评论