jsp动态生成静态网页

//制作人:fuweng

//模板文件

<Html>
<head>
<title>新闻展示</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>
<font color="red">新闻展示页面</font>
</h1>
<table style="width:500; border:0; align:center;">
<tr>
<td>新闻标题:###title###</td>
</tr>
<tr>
<td>作者:###author###&nbsp;&nbsp;</td>
</tr>
<tr>
<td>内容:###content###</td>
</tr>
</table>
</body>
</html> 

//Servlet获取jsp传递数据,并插入到模板文件的预留区域,来动态生成相应内容的静态网页

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String title=request.getParameter("title");   //获取标题
String content=request.getParameter("content"); //获取内容
String author=request.getParameter("author"); //获取作者
String filePath = "";
String midPath="\\staticHtml\\"; //jetty服务器运行的路径
//String midPath="staticHtml\\"; //tomcat服务器运行的路径
filePath = request.getRealPath("/")+midPath+"template.htm";  //模板文件的保存位置
String templateContent="";
System.out.print(filePath);
try{
FileInputStream fileinputstream = new FileInputStream(filePath);//读取模块文件
int lenght = fileinputstream.available();
System.out.print(lenght);
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
templateContent=templateContent.replaceAll("###title###",title); 
templateContent=templateContent.replaceAll("###content###",content);
templateContent=templateContent.replaceAll("###author###",author);//替换掉模块中相应的地方
// 根据时间得文件名
Calendar calendar = Calendar.getInstance();
String filename = String.valueOf(calendar.getTimeInMillis()) +".html";
String fileame = request.getRealPath("/")+midPath+filename;//生成的html文件保存路径
FileOutputStream fileoutputstream = new FileOutputStream(fileame);//建立文件输出流
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
response.sendRedirect("staticHtml\\"+filename);  //跳转到产生的静态网页
//response.sendRedirect(fileame);
//out.print("生成文件成功!!!");
return;
}catch( Exception e){
out.print("生成文件失败!!!");
}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值