静态化Html

public  String  staticContent(Integer cid){
Content content = contentService.get(cid);
if(content==null){
return "nofound";
}
FileOutputStream fos = null;
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext sc = ServletActionContext.getServletContext();
String staticUrl = content.getStaticUrl();
File targetFile = null;
try {
if(TzStringUtils.isNotEmpty(staticUrl)){
String path = request.getRealPath("/");
File rootPath = new File(path);
targetFile = new File(rootPath,staticUrl);
}else{
String ymd = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
String rpath = "pages/"+ymd;
String path = request.getRealPath(rpath);
File rootPath = new File(path);
if(!rootPath.exists())rootPath.mkdirs();
String name = cid+getRandomString(8)+".html"; 
targetFile = new File(rootPath,name);
staticUrl = rpath+"/"+name;
}
RequestDispatcher rd = sc.getRequestDispatcher("/template/content.jsp");
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final ServletOutputStream stream = new ServletOutputStream() {//匿名内部类,回调函数
public void write(byte[] data, int offset, int length) {
os.write(data, offset, length);
}
public void write(int b) throws IOException {
os.write(b);
}
};
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,"gbk"));
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return stream;
}


public PrintWriter getWriter() {
return pw;
}
};

//存放id
request.setAttribute("cid",cid);
rd.include(request, rep);//发起请求
pw.flush();
fos = new FileOutputStream(targetFile);
os.writeTo(fos);//讲源代码写入磁盘文件中
//静态化的url更新数据表中
content.setStaticUrl(staticUrl);
contentService.updateDefault(content);
return "success";
} catch (FileNotFoundException e) {
e.printStackTrace();
return "error";
} catch (ServletException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
}

private static String getRandomString(int length) {
StringBuffer bu = new StringBuffer();
String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
"d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q",
"r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C",
"D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
Random random = new Random();
while (bu.length() < length) {
String temp = arr[random.nextInt(57)];
if (bu.indexOf(temp) == -1) {
bu.append(temp);
}
}
return bu.toString();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值