您好,登錄后才能下訂單哦!
這篇文章主要介紹“freemarker靜態(tài)化生成html頁(yè)面亂碼怎么解決”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“freemarker靜態(tài)化生成html頁(yè)面亂碼怎么解決”文章能幫助大家解決問(wèn)題。
<!-- 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> <!-- 頁(yè)面數(shù)值的顯示格式 --> <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> <!-- 方便頁(yè)面獲得項(xiàng)目的絕對(duì)路徑 --> <property name="requestContextAttribute" value="request"></property> </bean>
然后是controller的核心代碼
@RequestMapping("/getHtml") public String getHtml(HttpServletRequest request,HttpServletResponse response) throws Exception{ //第一步 freemarkerConfigurer得到一個(gè)Configure對(duì)象 Configuration configuration = freeMarkerConfigurer.getConfiguration(); //第二步 得到一個(gè)模版文件 Template template = configuration.getTemplate("index.ftl"); //第三步 構(gòu)建數(shù)據(jù)模型 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()); //第四步 指定一個(gè)文件夾 構(gòu)建一個(gè)輸出流 String dir = request.getSession().getServletContext().getRealPath("/WEB-INF/"); //PrintWriter printWriter = new PrintWriter(new FileWriter(new File(dir,"index.html"))); System.out.println(dir); //第五步 數(shù)據(jù)模型+模版文件 = 輸出(控制臺(tái)輸出,html文件) template.process(map, printWriter); printWriter.flush(); return "success"; }
最后頁(yè)面提示成功生成html頁(yè)面
但在進(jìn)入生成的html頁(yè)面時(shí)發(fā)生了亂碼
首先是說(shuō)ftl文件的head上加上
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
因?yàn)槲以趕pringmvc的視圖解析器配置了
<property name="contentType" value="text/html;charset=utf-8"></property>
所以這個(gè)選擇首先pass掉,然后說(shuō)是在controller里加上
configuration.setDefaultEncoding("UTF-8");
不過(guò)因?yàn)槲以趂reemarker的環(huán)境配置我也配置了默認(rèn)的編碼
<!-- 編碼 --> <property name="defaultEncoding" value="utf-8"></property>
所以應(yīng)該也不是這個(gè)原因,后來(lái)我找到生成的html文件,發(fā)現(xiàn)用瀏覽器查看源代碼雖然會(huì)亂碼,但用記事本打開的時(shí)候所顯示并沒有亂碼,然后判斷是輸出流的問(wèn)題,通過(guò)網(wǎng)上查找發(fā)現(xiàn)FileWriter和FileReader使用的是系統(tǒng)默認(rèn)的編碼方式,因?yàn)閒ileWriter本身不具有用戶指定編碼的方式,這里選擇使用filewriter 的父類OutputStreamWriter來(lái)讀寫操作,把代碼
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);
后啟動(dòng)程序
導(dǎo)入坐標(biāo)
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
創(chuàng)建模板文件
<html> <head> <meta charset="utf-8"> <title>Freemarker入門</title> </head> <body> <#--我只是一個(gè)注釋,我不會(huì)有任何輸出 --> ${name}你好,${message} </body> </html>
生成文件
public static void main(String[] args) throws Exception{ //1.創(chuàng)建配置類 Configuration configuration=new Configuration(Configuration.getVersion()); //2.設(shè)置模板所在的目錄 configuration.setDirectoryForTemplateLoading(new File("D:\\ftl")); //3.設(shè)置字符集,讀取文件的編碼 configuration.setDefaultEncoding("utf-8"); //4.加載模板 Template template = configuration.getTemplate("test.ftl"); //5.創(chuàng)建數(shù)據(jù)模型 Map map=new HashMap(); map.put("name", "張三"); map.put("message", "歡迎來(lái)到中國(guó)!"); //6.創(chuàng)建Writer對(duì)象 // // 指定輸出編碼格式 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.關(guān)閉Writer對(duì)象 out.close(); }
分析
前面我們已經(jīng)學(xué)習(xí)了Freemarker的基本使用方法,下面我們就可以將Freemarker應(yīng)用到項(xiàng)目中,幫我們生成移動(dòng)端套餐列表靜態(tài)頁(yè)面和套餐詳情靜態(tài)頁(yè)面。
接下來(lái)我們需要思考幾個(gè)問(wèn)題:
(0)那些頁(yè)面應(yīng)該靜態(tài)化? 數(shù)據(jù)不經(jīng)常發(fā)生變化,訪問(wèn)量大的
(1)什么時(shí)候生成靜態(tài)頁(yè)面比較合適呢?
(2)將靜態(tài)頁(yè)面生成到什么位置呢?
(3)應(yīng)該生成幾個(gè)靜態(tài)頁(yè)面呢?
對(duì)于第一個(gè)問(wèn)題,應(yīng)該是當(dāng)套餐數(shù)據(jù)發(fā)生改變時(shí),需要生成靜態(tài)頁(yè)面,即我們通過(guò)后臺(tái)系統(tǒng)修改套餐數(shù)據(jù)(包括新增、刪除、編輯)時(shí)。
對(duì)于第二個(gè)問(wèn)題,如果是在開發(fā)階段可以將文件生成到項(xiàng)目工程中,如果上線后可以將文件生成到移動(dòng)端系統(tǒng)運(yùn)行的tomcat中。
對(duì)于第三個(gè)問(wèn)題,套餐列表只需要一個(gè)頁(yè)面就可以了,在這個(gè)頁(yè)面中展示所有的套餐列表數(shù)據(jù)即可。套餐詳情頁(yè)面需要有多個(gè),即一個(gè)套餐應(yīng)該對(duì)應(yīng)一個(gè)靜態(tài)頁(yè)面。
mobile_setmeal.ftl
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- 上述3個(gè)meta標(biāo)簽*必須*放在最前面,任何其他內(nèi)容都*必須*跟隨其后! --> <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>預(yù)約</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"> <!-- 頁(yè)面頭部 --> <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> <!-- 頁(yè)面內(nèi)容 --> <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"> <h5 class="ellipsis item-title">${setmeal.name}</h5> <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> <!-- 頁(yè)面 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個(gè)meta標(biāo)簽*必須*放在最前面,任何其他內(nèi)容都*必須*跟隨其后! --> <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>預(yù)約詳情</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"> <!-- 頁(yè)面頭部 --> <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> <!-- 頁(yè)面內(nèi)容 --> <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"> <h5 class="tit">${setmeal.name}</h5> <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="path2"></span><span class="path3"></span></i> <span>套餐詳情</span> </div> <div class="box-table"> <div class="table-title"> <div class="tit-item flex2">項(xiàng)目名稱</div> <div class="tit-item flex3">項(xiàng)目?jī)?nèi)容</div> <div class="tit-item flex3">項(xiàng)目解讀</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">立即預(yù)約</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工程中創(chuàng)建屬性文件freemarker.properties 通過(guò)上面的配置可以指定將靜態(tài)HTML頁(yè)面生成的目錄位置
out_put_path=靜態(tài)頁(yè)面生成的位置
在spring的中進(jìn)行配置
<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對(duì)應(yīng)的目錄 //新增套餐,同時(shí)關(guān)聯(lián)檢查組 public void add(Setmeal setmeal, Integer[] checkgroupIds) { setmealDao.add(setmeal); Integer setmealId = setmeal.getId();//獲取套餐id this.setSetmealAndCheckGroup(setmealId,checkgroupIds); //完成數(shù)據(jù)庫(kù)操作后需要將圖片名稱保存到redis jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg()); //當(dāng)添加套餐后需要重新生成靜態(tài)頁(yè)面(套餐列表頁(yè)面、套餐詳情頁(yè)面) generateMobileStaticHtml(); } //生成當(dāng)前方法所需的靜態(tài)頁(yè)面 public void generateMobileStaticHtml(){ //在生成靜態(tài)頁(yè)面之前需要查詢數(shù)據(jù) List<Setmeal> list = setmealDao.findAll(); //需要生成套餐列表靜態(tài)頁(yè)面 generateMobileSetmealListHtml(list); //需要生成套餐詳情靜態(tài)頁(yè)面 generateMobileSetmealDetailHtml(list); } //生成套餐列表靜態(tài)頁(yè)面 public void generateMobileSetmealListHtml(List<Setmeal> list){ Map map = new HashMap(); //為模板提供數(shù)據(jù),用于生成靜態(tài)頁(yè)面 map.put("setmealList",list); generteHtml("mobile_setmeal.ftl","m_setmeal.html",map); } //生成套餐詳情靜態(tài)頁(yè)面(可能有多個(gè)) 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); } } //通用的方法,用于生成靜態(tài)頁(yè)面 public void generteHtml(String templateName,String htmlPageName,Map map){ Configuration configuration = freeMarkerConfigurer.getConfiguration();//獲得配置對(duì)象 Writer out = null; try { Template template = configuration.getTemplate(templateName); //構(gòu)造輸出流 // 中文亂碼 //out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (outPutPath + "/" + htmlPageName),"UTF-8")); //構(gòu)造輸出流 out = new FileWriter(new File(outPutPath + "/" + htmlPageName)); //輸出文件 template.process(map,out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
生成靜態(tài)頁(yè)面的通用方法
//通用的方法,用于生成靜態(tài)頁(yè)面(參數(shù):templateName:模板,htmlPageName:生成的文件名稱,Map:數(shù)據(jù)) public void generteHtml(String templateName,String htmlPageName,Map map){ Configuration configuration = freeMarkerConfigurer.getConfiguration();//獲得配置對(duì)象 Writer out = null; try { Template template = configuration.getTemplate(templateName); //構(gòu)造輸出流 // 中文亂碼 //out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (outPutPath + "/" + htmlPageName),"UTF-8")); //構(gòu)造輸出流 out = new FileWriter(new File(outPutPath + "/" + htmlPageName)); //輸出文件 template.process(map,out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
14 -測(cè)試
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); }
關(guān)于“freemarker靜態(tài)化生成html頁(yè)面亂碼怎么解決”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。