1.创建需要导出的html模板,我创的模板是template.html,放到项目WEB-INF/content下面。
<html>
<head>
<title>###title###</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>
<body>
###content###
</body>
</html>
2.工具类
public class JspToHtml {
/**
* 根据本地模板生成静态页面
* @param JspFile jsp路经
* @param HtmlFile html路经
* @return
*/
public static boolean JspToHtmlFile(String filePath, String title,String context,String fileName) {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
String str = "";
long beginDate = (new Date()).getTime();
try {
String tempStr = "";
FileInputStream is = new FileInputStream(filePath);//读取模块文件
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((tempStr = br.readLine()) != null)
str = str + tempStr ;
is.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
//新建文件
OutputStream out = null;
try {
str = str.replaceAll("###title###",title);
str = str.replaceAll("###content###",context);//替换掉模块中相应的地方
//否则,直接写到输出流中
out = response.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
fileName = fileName+".html";
response.setContentType("application/x-msdownload");
final String userAgent = request.getHeader("USER-AGENT"); //获取浏览器的代理
//下面主要是让文件名适应不同浏览器的编码格式
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")) {
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
}
response.setHeader("Content-Disposition", "attachment; filename=\"" +
finalFileName + "\"");
System.out.println("共用时:" + ((new Date()).getTime() - beginDate) + "ms");
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
3.调用
//导出html
//获得项目的根路径
String path = request.getSession().getServletContext().getRealPath("/");
//将根路径与模板地址拼接,从而才能找到html模板
String url = path+"WEB-INF\\content\\template.html";//模板文件根地址
//标题,对应模板中###title###
String title = "标题";
//内容,对应模板中###context###
String context = "内容";
//导出的html的名字+时间戳
String fileName = "名字"+System.currentTimeMillis();
JspToHtml c = new JspToHtml();
c.JspToHtmlFile(url, title, context, fileName);
4.完成