jsp动态生成静态网页

来源:互联网 发布:java加密软件 编辑:程序博客网 时间:2024/05/21 06:49

//制作人: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("生成文件失败!!!");
}
}
原创粉丝点击