利用HtmlClient生成静态页面

来源:互联网 发布:淘宝秒刷销量一天千单 编辑:程序博客网 时间:2024/05/01 00:03


 直接上代码

 

发布新闻方法:

 

@Action(value = "publisNews", results = {@Result(name = "toBrowseNews", type = "redirectAction", location = "newsQuery") })/** 发布指定新闻 */public String publisNews() throws Exception{if (model.getId()!=null){News tempNews = newsService.getNewsById(model.getId());if (tempNews!=null){HttpServletRequest request = ServletActionContext.getRequest();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();String url=basePath+"/news/viewNews.action?id="+tempNews.getId();//创建静态页面生成器实例HtmlGenerator hg = new HtmlGenerator(basePath);//发布成静态页面if (hg.createHtmlPage(url, request.getRealPath(tempNews.getHtmlPath()))){actionMsg = getText("news_publish_succ");//将该新闻标记成"已发布"tempNews.setStatus(Dictionary.NEWS_STATUS_YES);}else{actionMsg = getText("news_publish_fail");//将该新闻标记成"未发布"tempNews.setStatus(Dictionary.NEWS_STATUS_NO);}newsService.updateNews(tempNews);//调用业务逻辑组件更新指定的新闻}}return "toBrowseNews";}  


 

 HtmlGenerator类:

 

package com.west2.common.util.htmlClient;import java.io.*;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.*;import org.apache.commons.httpclient.params.HttpMethodParams;/** 静态页面引擎 */public class HtmlGenerator extends BaseLog {HttpClient httpClient = null; //HttpClient实例GetMethod getMethod =null; //GetMethod实例BufferedWriter fw = null;String page = null;String webappname = null;BufferedReader br = null;InputStream in = null;StringBuffer sb = null;String line = null;//构造方法public HtmlGenerator(String webappname){this.webappname = webappname;}/** 根据模版及参数产生静态页面 */public boolean createHtmlPage(String url,String htmlFileName){boolean status = false;int statusCode = 0;try{//创建一个HttpClient实例充当模拟浏览器httpClient = new HttpClient();//设置httpclient读取内容时使用的字符集httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");//创建GET方法的实例getMethod = new GetMethod(url);//使用系统提供的默认的恢复策略,在发生异常时候将自动重试3次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());//设置Get方法提交参数时使用的字符集,以支持中文参数的正常传递getMethod.addRequestHeader("Content-Type","text/html;charset=UTF-8");//执行Get方法并取得返回状态码,200表示正常,其它代码为异常statusCode = httpClient.executeMethod(getMethod);if (statusCode!=200) {logger.fatal("静态页面引擎在解析"+url+"产生静态页面"+htmlFileName+"时出错!");}else{//读取解析结果sb = new StringBuffer();in = getMethod.getResponseBodyAsStream();br = new BufferedReader(new InputStreamReader(in,"UTF-8"));while((line=br.readLine())!=null){sb.append(line+"\n");}if(br!=null)br.close();page = sb.toString();//将页面中的相对路径替换成绝对路径,以确保页面资源正常访问page = formatPage(page);//将解析结果写入指定的静态HTML文件中,实现静态HTML生成writeHtml(htmlFileName,page);status = true;}}catch(Exception ex){logger.fatal("静态页面引擎在解析"+url+"产生静态页面"+htmlFileName+"时出错:"+ex.getMessage());        }finally{        //释放http连接        getMethod.releaseConnection();        }return status;}//将解析结果写入指定的静态HTML文件中private synchronized void writeHtml(String htmlFileName,String content) throws Exception{fw = new BufferedWriter(new FileWriter(htmlFileName));fw.write(page);if(fw!=null)fw.close();}//将页面中的相对路径替换成绝对路径,以确保页面资源正常访问private String formatPage(String page){page = page.replaceAll("\\.\\./\\.\\./\\.\\./", webappname+"/");page = page.replaceAll("\\.\\./\\.\\./", webappname+"/");page = page.replaceAll("\\.\\./", webappname+"/");return page;}//测试方法public static void main(String[] args){HtmlGenerator h = new HtmlGenerator("");h.createHtmlPage("http://www.qq.com","c:/a.html");}}

 

 

BaseLog:

package com.west2.common.util.htmlClient;import org.apache.log4j.*;public class BaseLog { /** 取得日志记录器Logger */ public Logger logger = Logger.getLogger(BaseLog.class);}


 

原创粉丝点击