分享

本栏目文章静态化

 Blex 2011-05-09
package cn.com.voc.tv.servlet.article;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.voc.tv.dao.ArticleDao;
import cn.com.voc.tv.dao.NavDao;
import cn.com.voc.tv.dao.TemplateDao;
import cn.com.voc.tv.po.Article;
import cn.com.voc.tv.po.Nav;
import cn.com.voc.tv.util.StringUtil;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
public class Article_ToHtml extends HttpServlet {
 /**
  *
  */
 private static final long serialVersionUID = 1L;
 
 
 /**
  * Constructor of the object.
  */
 public Article_ToHtml() {
  super();
 }
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }
 
 
 
 /**
  * 根据栏目Id生成静态文件
  * @param int navId
  * @return
  */
 private String toHtmlByNavId(int navId){
  
  NavDao ndao = new NavDao();
  TemplateDao tdao = new TemplateDao();
  ArticleDao atcDao = new ArticleDao();
  
  Nav n = ndao.getNavbyId(navId);
  File outFolder = new File(this.getServletContext().getRealPath("/")+n.getStaticHtmlFolder());
  
  if(!outFolder.exists()) //建立输出目录
  {
   outFolder.mkdirs();
  }
  
  
  Configuration cfg = new Configuration();
  
  
  /* 设置读取模板文件的目录 */
  cn.com.voc.tv.po.Template tplt = null; 
    
  if(n!=null){
   tplt = tdao.getTemplateById(n.getTemplateId());
   try {
    cfg.setDirectoryForTemplateLoading(new File(this.getServletContext().getRealPath("/")+tplt.getSavePath())); 
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
  
  int colWordCount = tplt.getColWordCount(); //获取模板设置信息
  int rowCount = tplt.getRowCount();
  int allowPageLen = colWordCount*rowCount;
  
  
  Article atc = null;
  
  /* 本栏目文章列表 */
  List atcList = atcDao.findByRootId(navId);
  StringBuffer message =  new StringBuffer("<font color='red'>没有数据,生成失败!</font>");
  
  
  if(atcList!=null)
  {
   message =  new StringBuffer("");
   
   for(int j=0;j<atcList.size();j++) 
   {
    atc = (Article) atcList.get(j);
    
    String prevPage = atcDao.getPrevPageLinkByAtcId(atc);
    String nextPage = atcDao.getNextPageLinkByAtcId(atc);
    
    
    /* 将文章内容根据每页容纳的长度解析成数组  */
    String content = atc.getContent(); 
    ArrayList ctntList = new ArrayList();
    
    allowPageLen = allowPageLen-1;
    int k = allowPageLen;   //步长
    int allowLen = 0;
    if(content.length()%allowPageLen>0)
    {
     allowLen = content.length()/allowPageLen+content.length()%allowPageLen;
    }
    
    for(int i=0;i<(content.length()+allowPageLen);i+=allowPageLen)
    {
     String tpct = "";
     if(i>content.length())
     {
      i = content.length();
     }
     if(k>atc.getContent().length())
     {
      k = atc.getContent().length();
      tpct = content.substring(i, k);
      if(tpct!=null)
      {
       ctntList.add(tpct);
      }
      break;
     }else{
      tpct = content.substring(i, k);
     }
     
     if(tpct!=null)
     {
      ctntList.add(tpct);
     }
     
     k += allowPageLen;
    }
        
    
    
    /**
     *   根据内容列表生成静态Html到栏目指定的目录。
     *  模板、导出目录由栏目设定,模板设定每页内容的长度。
     * 在进行生成操作之前,先设定导出目录,和栏目模板,并在模板中设定每页内容的行数,列数
     */
    
    for(int i=0;i<ctntList.size();i++) //内容列表
    {
     HashMap root = new HashMap();
     root.put("title",atc.getTitle() );
     
     String s = (String) ctntList.get(i);
     s = StringUtil.toHTML(s);
     
     String[] temp_basename = atc.getStaticHtmlName().split("\\.");
     String fileBaseName = temp_basename[0];
     String fileName = "";
     
     
     String preBaseName= "";
     String nexBaseName = "";
     if(prevPage!=null){
      preBaseName = prevPage.split("\\.")[0]; 
     }
     if(nextPage!=null)
     {
      nexBaseName = nextPage.split("\\.")[0]; 
     }
     
     
     /**
      * 内容页面的prevPage,nextPage链接分析
      */
        if(i==0&&ctntList.size()==1) //只有一页内容
        {
         if(!preBaseName.equals(""))
         {
          root.put("prevPage", preBaseName+"_0.html");
         }else{
          root.put("prevPage","");
         }
         if(!nexBaseName.equals(""))
         {
          root.put("nextPage", nexBaseName+"_0.html");
         }else{
          root.put("nextPage", "");
         }
         
         root.put("content", ctntList.get(0));
         fileName = fileBaseName+"_0.html";
        }
        else if(i==0&&ctntList.size()>1)
        { //第一个文件
         
         if(!preBaseName.equals(""))
         {
          root.put("prevPage", preBaseName+"_0.html");
         }else{
          root.put("prevPage","");
         }
        
         root.put("nextPage",fileBaseName+"_"+1+".html");
         
          root.put("content", ctntList.get(i));
        
          fileName = fileBaseName+"_0.html";
        }
        else if(i==(ctntList.size()-1)&&ctntList.size()>1)
        {//最后一个文件
      String prep = fileBaseName+"_"+(i-1)+".html"; //前一页的文件名
      root.put("prevPage",prep);
        
      if(!nexBaseName.equals(""))
      {
        root.put("nextPage",nexBaseName+"_0.html"); //下一页的文件名,即nextPage
      }else{
        root.put("nextPage",""); //下一页的文件名,及nextPage
      }
      
      root.put("content", ctntList.get(i));
      
      fileName = fileBaseName+"_"+i+".html";
        }
        else
        { //中间生成的文件
          String prep = fileBaseName+"_"+(i-1)+".html";
          String nexp = fileBaseName+"_"+(i+1)+".html";
         
          root.put("prevPage",prep);
          root.put("nextPage",nexp); //下一页的文件名,及nextPage
          root.put("content",ctntList.get(i));
         
          fileName = fileBaseName+"_"+i+".html";
        }
     
     
        /* 读取模板,设定输出 */
       
     freemarker.template.Template t = null;
     Writer out = null;
     try {
      t = cfg.getTemplate(tplt.getFileName());
      out = new OutputStreamWriter(new FileOutputStream(outFolder+"/"+fileName), "gbk");  //输出流
     } catch (IOException e1) {
      e1.printStackTrace();
     }
     
     
     
     /**
      * 生成
      */
     try {
         t.process(root, out);
         message.append("<font color='green'>成功生成"+outFolder+"/"+fileName+"</font><br/>");
        
     } catch (IOException e) {
      e.printStackTrace();
     }
     catch (TemplateException e) {
      message.append("<font color='red'>"+outFolder+"/"+fileName+"生成失败</font><br/>");
      e.printStackTrace();
     }
     
    }//end 遍历内容数组
    
   }//end for 文章列表
   
    
   
   /**
    * 生成本栏目listArray.js数组
    */
   String mess = generatDataJS(atcList,outFolder.toString());
   
   message.append("<br/><br/>");
   message.append(mess);
   
  }//end if(atcList!=null)
  
  
  ndao.closeConnection();
  tdao.closeConnection();
  atcDao.closeConnection();
  
  return message.toString();
  
  
 }
 
 
 
 /***
  * 生成成数据listArray.js文件
  * @param ArrayList atcList,String filePath
  * @return String message
  */
 private String generatDataJS(List atcList,String filepath)
 {
  
  StringBuffer sb = new StringBuffer("var listArray = [\n");
  
  for(int i=0;i<atcList.size();i++)
  {
   Article atc = (Article) atcList.get(i);
   String title = atc.getTitle();
   
   String htm = atc.getStaticHtmlName();
   htm = htm.split("\\.")[0]+"_0.html";
   
   sb.append("{\"info\":\"★"+title+"\",");
   sb.append("\"url\":\""+htm+"\"},\n");
  }
  sb.append("];");
  
  
  if(sb.lastIndexOf(",")>0)
  {
   sb.deleteCharAt(sb.lastIndexOf(","));
  }
  
  File dir,f;
  dir = new File(filepath);
  if(!dir.exists()){ dir.mkdirs(); }
  
  f = new File(filepath+"/listArray.js");
  if(f.exists()){
   f.delete();
  }
  
  try {
   f.createNewFile();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  try {
   FileWriter resultFile = new FileWriter(f); //输出文件
   PrintWriter pw = new PrintWriter(resultFile);
   pw.println(sb);
   pw.close();
   
   return "<font color='green'>数组文件生成成功!</font>";
   
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  
  return "<font color='red'>数组文件生成失败!<font>";
 }
 
 
 
 
 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   
  this.doPost(request, response);
   
 }
 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String fromURL = request.getParameter("fromURL");
  
  String type = request.getParameter("type");
  String navId = request.getParameter("navId");
  
  String message = "";
  if("nav".equals(type)){
   int id = Integer.parseInt(navId);
   message = toHtmlByNavId(id);
  }
  
  
  
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY><center>");
  
  out.print(message);
  
  out.print("<meta http-equiv=refresh content=2;url="+fromURL+">");
  
  out.println("</center></BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多