代码改变世界

freemark中文乱码问题

2013-12-03 13:41  夜半花开  阅读(396)  评论(0)    收藏  举报

网上搜了好多资料,自己用的freemark方法如下:

模板页:

<div>
<form action="" method="post">
<table width="100%" border="0" cellspacing="0" cellpadding="0"
class="t5 color333" bgcolor="#FFFFFF">
<tr>
<td width="100%" height="35" style="text-align:center;padding-right:40px;">
###title###
</td>
</tr>
<tr>
<td width="100%" height="35" style="text-align:center;padding-right:20px;">
###author###
</td>
</tr>
<tr>
<td width="100%" height="35" style="text-align:center;padding-right:20px;">
###context###
</td>
</tr>
</table>
</form>
</div>

 

action代码

@Action(value = "newshtml")

public String newshtml()
{

String title=this.getRequest().getParameter("title");
String author=this.getRequest().getParameter("author");
String context=this.getRequest().getParameter("context");
try {
title=new String(title.getBytes("ISO-8859-1"),"UTF-8");
author=new String(author.getBytes("ISO-8859-1"),"UTF-8");
context=new String(context.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SimpleDateFormat sip=new SimpleDateFormat("yyyyMMdd hhmmss");
Date date=new Date();
String filepath=ServletActionContext.getServletContext().getRealPath("/")+"WEB-INF\\content\\manager\\pfairmanager\\news.html";
String htmlpath=ServletActionContext.getServletContext().getRealPath("/")+sip.format(date)+".html";
String str = "";
long beginDate = (new Date()).getTime();
try {
String tempStr = "";
FileInputStream is = new FileInputStream(filepath);//读取模块文件
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
while ((tempStr = br.readLine()) != null)
str = str + tempStr ;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {

str = str.replaceAll("###title###",title);
str = str.replaceAll("###author###",author);
str = str.replaceAll("###context###",context);//替换掉模块中相应的地方

File f = new File(htmlpath);
//BufferedWriter o = new BufferedWriter(new FileWriter(f));
BufferedWriter o = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"UTF-8"));
o.write(str);
o.close();
System.out.println("共用时:" + ((new Date()).getTime() - beginDate) + "ms");
PrintWriter out=this.getResponse().getWriter();
out.print(htmlpath);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}