xslt 静态化页面的生成程序

来源:互联网 发布:什么是数据漫游 编辑:程序博客网 时间:2024/04/30 07:55
用 xslt 生成 静态页面 ,遍历数据库中的数据 ,使得访问速度大大加快,对搜索引擎优化也有好处.
下面是配置文件
<?xml version="1.0" encoding="GBK" ?>
- <Config>
  <cpDataFile>CPConfig/CpData.xml</cpDataFile>
  <xsltFile>CPConfig/Page.xslt</xsltFile>
  <xsltFileM>CPConfig/PageM.xslt</xsltFileM>
  <lsServerPath>你的数据库调用方式</lsServerPath>
  <fileType>.html</fileType>
  <rootPath>Static/html/</rootPath>
  <rootUrl>/html/</rootUrl>
  <exMatLogo>exLog.txt</exMatLogo>
- <nearInfo>
- <nearlyItems>
  <words>餐饮美食</words>
  <itemNumber>10</itemNumber>
  <itemRadius>5000</itemRadius>
  </nearlyItems>
- <nearlyItems>
  <words>宾馆饭店</words>
  <itemNumber>10</itemNumber>
  <itemRadius>5000</itemRadius>
  </nearlyItems>
- <nearlyItems>
  <words>娱乐休闲</words>
  <itemNumber>10</itemNumber>
  <itemRadius>5000</itemRadius>
  </nearlyItems>
- <nearlyItems>
  <words>购物商场</words>
  <itemNumber>10</itemNumber>
  <itemRadius>5000</itemRadius>
  </nearlyItems>
  </nearInfo>
  </Config>
下面是主程序 java xslt 生成文件 结合上面的 config.xml
main函数运行
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

import com.lingtu.appdata.oper.AppDataXML;


/**
 *
 * CP 静态化  *
 * @author 柴琦 chaiqi1@hotmail.com
 *
 * @Des 
 *
 CP 提供如下 格式的xml格式
 <?xml version="1.0" encoding="gbk"?>
 <PoiInfo>
 <Poi id="1">
 <ExNa v="北京建国饭店" />
 <ExCity v="北京" />
 <ExUrl v="http://www.elong.com/pid=123456" />
 <ExDes v="味道相当不错" />
 </Poi>
 <Poi id="2">
 <ExNa v="昆仑饭店" />
 <ExCity v="北京" />
 <ExUrl v="http://www.elong.com/pid=22222" />
 <ExDes v="气势雄伟很是美观" />
 </Poi>
 </PoiInfo>
 
 我们通过程序 把这些 文件 按照一定规格的 xslt 生成静态文件 .兼容 Detail *
 */

public class CpDetailOper {
 
 /**
  * 常用静态化变量
  */
 //cp data xml
 private static String cpDataFile="E:/51DITU_WorkProgram/LT51DITU_WWW_DETAIL_tomcat/src/com/lingtu/detail/cp/CpTest.xml";
 //xslt文件
 private static String xsltFile="E:/51DITU_WorkProgram/LT51DITU_WWW_DETAIL_tomcat/src/com/lingtu/detail/cp/Page.xslt";
 private static String xsltFileM="PageM.xslt";
 //ls引擎
 private static String lsServerPath = "http://172.16.74.131/LocalSearch?";
 //生成html后缀
 private static String fileType = ".html";
 //存放静态文件的路径
 private static String rootPath = "e:/static/html/";
 //静态连接url
 private static String rootUrl = "/html/";
 //ex匹配log地址
 private static String exMatLogo ="e:/static/html/errLog.txt";
 
 //附近周边搜索
 private static String nearlyItems[];
 private static int nearlyItemNumbers[];
 private static int nearlyItemRadius[];
 //输出DOMOutputter
 private DOMOutputter outputter = new DOMOutputter();
 //xslt转化器
 private Transformer processor,processorM;
 private static SAXBuilder builder = new SAXBuilder();
 
 //匹配上的列表
 private static ArrayList exList = new ArrayList();
 
 //运行起止时间
 private static String startTime ="";
 private static String endTime ="";
 
 
 
 
 /**
  * 读取配置文件,进行初始化
  * @param args
  * @return
  */
 public static boolean readConfigFile(String configpath)
 {
  if(configpath.equals("")){
   System.out.println("Sorry,configFile is empty!");
   return false;
  }
  File configFile = new File(configpath);
  
  try
  {
   Document doc = builder.build(configFile);
   
   Element node = (Element)XPath.selectSingleNode(doc, "/Config/cpDataFile");
   if(node != null)
    cpDataFile = node.getText();
   node = (Element)XPath.selectSingleNode(doc, "/Config/xsltFile");
   if(node != null)
    xsltFile = node.getText();
   node = (Element)XPath.selectSingleNode(doc, "/Config/xsltFileM");
   if(node != null)
    xsltFileM = node.getText();
   node = (Element)XPath.selectSingleNode(doc, "/Config/lsServerPath");
   if(node != null)
    lsServerPath = node.getText();
   node = (Element)XPath.selectSingleNode(doc, "/Config/fileType");
   if(node != null)
    fileType = node.getText();
   
   node = (Element)XPath.selectSingleNode(doc, "/Config/rootUrl");
   if(node != null)
    rootUrl = node.getText();
   
   node = (Element)XPath.selectSingleNode(doc, "/Config/rootPath");
   if(node != null)
    rootPath = node.getText();
   
   node = (Element)XPath.selectSingleNode(doc, "/Config/exMatLogo");
   if(node != null)
    exMatLogo = node.getText();
   
   
   File file = new File(rootPath);
   if(!file.isDirectory() || !file.exists())
   {
    System.out.println("Sorry,rootPath is not exists");
    return false;
   }
   
   node = (Element)XPath.selectSingleNode(doc, "/Config/nearlyItemNumber");
   List list = XPath.selectNodes(doc, "/Config/nearInfo/nearlyItems");
   int number = list.size();
   if(list.size() > 0)
   {
    nearlyItems = new String[number];
    nearlyItemNumbers = new int[number];
    nearlyItemRadius = new int[number];
    for(int i = 0; i < number; i++)
    {
     node = (Element)list.get(i);
     nearlyItems[i] = node.getChildTextTrim("words");
     if(node.getChild("itemNumber") != null)
      nearlyItemNumbers[i] = Integer.parseInt(node.getChildTextTrim("itemNumber"));
     else
      nearlyItemNumbers[i] = 10;
     if(node.getChild("itemRadius") != null)
      nearlyItemRadius[i] = Integer.parseInt(node.getChildTextTrim("itemRadius"));
     else
      nearlyItemRadius[i] = 10;
    }
    
   }
  }
  catch(Exception e)
  {
   System.out.println(e.getMessage());
   System.out.println("Read Config File File");
   return false;
  }
  
  System.out.println("Read Config File OK");
  return true;
 }
 
 
 /**
  * 主程序 转换
  * @param cpxml_path
  */
 public void cpDataAddLs(){
  
  //转换计时
  startTime = (new Date()).toString();
  System.out.println("结束时间: "+startTime);
  
  try {
   InputStream in = null;
   SAXBuilder builder = new SAXBuilder();
   
   //解析cpdata信息
   Document requestDoc = null;
   requestDoc = builder.build(cpDataFile);
   Element root = (Element)requestDoc.getRootElement();
   Iterator list = root.getChildren().iterator();
   while(list.hasNext()) {
    
    //1-取得cpdata中1条城市和名称信息
    Element node = (Element) list.next();
    String ExCity="";
    String ExNa="";
    String ExUrl="";
    String ExDes="";
    String LsID="";
    String lsIDPath="";
    String LsIDFolPath="";
    String lo="";
    String la="";
    
    if (node.getChild("ExNa") != null) {
     ExNa = node.getChild("ExNa").getAttributeValue("v");
    }
    if (node.getChild("ExCity") != null) {
     ExCity = node.getChild("ExCity").getAttributeValue("v");
    }
    
    //2-完全匹配查询ls看数据中是否存在cpdata信息
    Element lsnode = lsSearch(ExCity,ExNa);
    
    //2.1简单猜词名称过滤
    if(lsnode==null){
     int nameIndofCity = ExNa.indexOf(ExCity);
     if(nameIndofCity==0){
      ExNa = ExNa.substring(nameIndofCity+ExCity.length());
      lsnode = lsSearch(ExCity,ExNa);
     }
    }
    
    if(lsnode!=null){
     
     if (lsnode.getChild("LSID") != null) {
      
      LsID = lsnode.getChild("LSID").getAttributeValue("v");
      lo = lsnode.getChild("Geo").getAttributeValue("lo");
      la = lsnode.getChild("Geo").getAttributeValue("la");
      lsIDPath=LsID;
      //创建文件夹
      LsIDFolPath = LsID.substring(0,LsID.lastIndexOf("/"));
      LsIDFolPath = new StringBuffer(rootPath).append(LsIDFolPath).toString();
      createFolder(new File(LsIDFolPath),false);
      
      LsID = LsID.substring(LsID.lastIndexOf("/")+1);
      //查询出一个Poi点
      requestDoc = getOnePoi(LsID);
      requestDoc.getRootElement().addContent(node.getChild("ExNa").detach());
      requestDoc.getRootElement().addContent(node.getChild("ExCity").detach());
      
      /**
       * 周边查找插入
       */
      Element nearInfo = new Element("nearInfo");
      requestDoc.getRootElement().addContent(nearInfo);
      for(int i = 0; i < nearlyItems.length; i++)
      {
       
       Document infoDoc = builder.build(lsServerPath + "LocalSearch&city="+ExCity+"&area=POINT(" + lo + "%20" + la + ")&radius=" + nearlyItemRadius[i] + "&start=1&pagecap=" + nearlyItemNumbers[i] + "&words=" + nearlyItems[i]);
       Element nearNode = infoDoc.detachRootElement();
       nearNode.setName("NearlyItems");
       nearNode.setAttribute("words", nearlyItems[i]);
       nearInfo.addContent(nearNode);
      }
      
      TransformerFactory transformerFactory =TransformerFactory.newInstance();
      Templates stylesheet = transformerFactory.newTemplates(new StreamSource(xsltFile));
      Templates stylesheetM = transformerFactory.newTemplates(new StreamSource(xsltFileM));
      processor = stylesheet.newTransformer();
      processorM = stylesheetM.newTransformer();
      
      DOMSource ds=new DOMSource(outputter.output(requestDoc));
      processor.transform(ds,new StreamResult(new StringBuffer(rootPath).append(lsIDPath).append(fileType).toString()));
      processorM.transform(ds,new StreamResult(new StringBuffer(rootPath).append(lsIDPath).append("m").append(fileType).toString()));
      
      //添加cp匹配纪录
      exList.add(new StringBuffer(ExCity).append(",").append(ExNa).toString());
      
     }
    }
    
   }
   
   //转换计时
   endTime = (new Date()).toString();
   System.out.println("结束时间: "+endTime);
   
   //写日志
   ExtoLogo();
   
   
  } catch (Exception e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
   ExtoLogo();
  }
 }
 
 
 /**
  * 返回一个poi,obtion 的 Document
  * @param lsid
  * @return
  */
 public static Document getOnePoi(String lsid){
  
  Document requestDoc = null;
  try {
   URL url = new URL(new StringBuffer(lsServerPath).append("Obtain&LSID=").append(lsid).toString());
   InputStream in = null;
   URLConnection conn = url.openConnection();
   conn.setDoInput(true);
   conn.setDoOutput(true);
   in = conn.getInputStream();
   
   // 请求URL网络连接失败
   if (in == null) {    
    System.out.println("LS引擎地址错误");
    return null;
   }
   
   BufferedReader inReader = new BufferedReader(new InputStreamReader(
     in, "GBK"));
   // 返回的XML
   StringBuffer strBuffer = new StringBuffer();
   
   for (String line = null; (line = inReader.readLine()) != null;) {
    strBuffer.append(line + "/n");
   }
   inReader.close();
   in.close();
   
   // 初始化XML解析
   SAXBuilder builder = new SAXBuilder();
   requestDoc = builder.build(new StringReader(strBuffer.toString()));
   
  } catch (Exception e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
   return null;
  }
  return  requestDoc;
  
 }
 
 /**
  * ls 查询到的ele结果
  * @param city
  * @param name
  * @return
  */
 public static Element lsSearch(String city,String name){
  
  Element node=null;
  try{
   
   URL url = new URL(new StringBuffer(lsServerPath).append("LocalSearch&city=").append(city).append("&words=").append(name).append("&mode=1&pagecap=1").toString());
   InputStream in = null;
   URLConnection conn = url.openConnection();
   conn.setDoInput(true);
   conn.setDoOutput(true);
   in = conn.getInputStream();
   // 请求URL网络连接失败
   if (in == null) {    
    System.out.println("LS引擎地址错误");
    return null;
   }
   
   BufferedReader inReader = new BufferedReader(new InputStreamReader(
     in, "GBK"));
   // 返回的XML
   StringBuffer strBuffer = new StringBuffer();
   
   for (String line = null; (line = inReader.readLine()) != null;) {
    strBuffer.append(line + "/n");
   }
   inReader.close();
   in.close();
   
   // 初始化XML解析
   SAXBuilder builder = new SAXBuilder();
   Document requestDoc = null;
   requestDoc = builder.build(new StringReader(strBuffer.toString()));
   
   // 错误结果处理
   Element root = requestDoc.getRootElement();
   Element ele = root.getChild("PoiRes");
   int errorCode = Integer.parseInt(root.getAttributeValue("error"));
   if (errorCode > 0) {    
    System.out.println("搜索出现错误!"+name+","+city);
    return null;
   }
   if (ele == null) {    
    // 查询不到结果处理
    //System.out.println("LS没有查询到符合条件的结果,url为:/n" + url.toString());
    return null;
   }
   //如果结果为0 return null
   int recordCount = Integer.parseInt(ele.getAttributeValue("total"));
   if(recordCount==0){

    return null;
   }
   Iterator list = ele.getChildren().iterator();
   node = (Element) list.next();
   
  } catch (Exception e) {
   System.out.println(city+","+name);
   e.printStackTrace();
  }
  return node;
 }
 
 /**
  * 创建文件夹, file为文件用true, file 为文件夹用false
  * @param file
  * @param flag
  */
 public static void createFolder(File file, boolean flag)
 {
  if(flag)
   createFolder(new File(file.getParent()), false);
  else
   if(!file.exists())
   {
    createFolder(new File(file.getParent()), false);
    file.mkdir();
   }
 }
 
 
 /**
  * 写 Exlog
  * @return
  */
 public boolean ExtoLogo(){
  StringBuffer str = new StringBuffer();
  if(exList!=null){
   str.append("总共匹配到 "+ exList.size()+" 条CP点。"+"/n").append("时间:").append(startTime).append("---").append(endTime+"/n/n");
   if(exList.size()>0){
    for(int i=0;i<exList.size();i++){
     str = str.append(exList.get(i).toString()+"/n");
    }
   }
  }
  try {
   FileOutputStream fos = new FileOutputStream(exMatLogo);
   Writer outs = new OutputStreamWriter(fos, "GB2312");
   outs.write(str.toString());
   outs.close();
  } catch (Exception e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
   return false;
  }
  return true;
  
 }
 
 
 
 /**
  *
  * 运行程序
  * E:/51DITU_WorkProgram/LT51DITU_WWW_DETAIL_tomcat/src/com/lingtu/cp/config.xml
  */
 
 /**
  * 本机调试程序
  */
// public static void main(String argv[]){
// CpDetailOper test = new CpDetailOper();
// test.readConfigFile("E:/51DITU_WorkProgram/LT51DITU_WWW_DETAIL_tomcat/src/com/lingtu/cp/config.xml");
// test.cpDataAddLs();
// }
 
 /**
  * linux运行程序
  */
 public static void main(String argv[]){
  
  if(argv.length < 1)
  {
   System.out.println("Sorry,Wrong arguments number");
   return;
  }else{
   CpDetailOper test = new CpDetailOper();
   test.readConfigFile(argv[0]);
   test.cpDataAddLs();
  }
  
 }
 
 
}

xslt文件 Page.xslt

<?xml version="1.0" encoding="GB2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="gb2312"/>
<xsl:template match="/">
<xsl:variable name="searchCity">
<xsl:choose>
<xsl:when test="contains(Poi/Admin/@pro,'市')"><xsl:value-of select="Poi/Admin/@pro"/></xsl:when>
<xsl:when test="Poi/Admin/@city"><xsl:value-of select="Poi/Admin/@city"/></xsl:when>
<xsl:when test="contains(Poi/@city,'市')"><xsl:value-of select="Poi/@city"/></xsl:when>
</xsl:choose>
</xsl:variable>
<html>
<head><title><xsl:value-of select="Poi/Na/@v" />_51ditu本地搜索结果</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<link href="http://www.51ditu.com/comm/css/comm.css" rel="stylesheet" type="text/css"/>
<link href="{Poi/@imgPath}style.css" rel="stylesheet" type="text/css"/>
<script language="javascript" src="http://www.51ditu.com/ls/js/indCit.js"></script>
<script language="javascript" src="{Poi/@imgPath}page.js"></script>
</head>
<body onload="init()">
<table width="758" align="center"><tr><td>
<script language="javascript" src="{Poi/@imgPath}head.js"></script>
</td></tr></table>

<table width="758" align="center" cellpadding="0" cellspacing="0"><tr>
 <td width="520"></td>
 <td><img src="{Poi/@imgPath}print.jpg" width="16" height="16" border="0"/></td>
 <td><a class="blue" href="javascript:window.print()">打印此页</a></td>
 <td width="2"></td>
 <td><img src="{Poi/@imgPath}save.jpg" width="16" height="16" border="0"/></td>
 <td><a class="blue" href="#" onclick="javascript:window.external.addFavorite(self.location,'{Poi/Na/@v}')">收藏此页</a></td>
 <td width="2"></td>
 <td><img src="{Poi/@imgPath}email.jpg" width="16" height="16" border="0"/></td>
 <td><a class="blue" href="#" onclick="self.location='mailto:yourfriend@51ditu.com?subject={Poi/Na/@v}--51ditu.com&amp;body='+self.location">发送给朋友</a></td>
</tr></table>

<table width="758" align="center"><tr><td valign="top">
 <table width="512" height="260" cellpadding="0" cellspacing="0">
  <tr><td>
   <table width="500" height="260" class="slide" cellpadding="0" cellspacing="0">
   <tr><td height="27" bgcolor="#E32925">
    <table><tr>
    <td width="18"><img src="{Poi/@imgPath}point.jpg" valign="middle" width="18" height="18"/></td>
    <td class="nameBar"><xsl:value-of select="Poi/Na/@v" /></td>
    </tr></table>
   </td></tr>
   <tr><td bgcolor="#FFFFFF" style="padding:15px;">
    <!-- <table><tr><td width="30%"><img src="{Poi/ExPhoto/@v}"/></td><td width="70%">地址:<xsl:value-of select="/Poi/Add/@v" /><br/>电话:<xsl:value-of select="/Poi/Tel/@v" /><br/>类别:<xsl:value-of select="/Poi/Class/@g1" />><xsl:value-of select="/Poi/Class/@g2" />><xsl:value-of select="/Poi/Class/@g3" /><br/>行政区划:<xsl:value-of select="/Poi/Admin/@pro" />><xsl:value-of select="/Poi/Admin/@city" />><xsl:value-of select="/Poi/Admin/@dis" /></td></tr></table> -->
    <table width="100%" style="padding:10px;">
     <tr>
      <td rowspan="5" width="40%" >
       <img src="{Poi/ExPhoto/@v}"/>
      </td>
      <td style="padding-left:15px;">
       类别:<xsl:value-of select="/Poi/Class/@g1" />><xsl:value-of select="/Poi/Class/@g2" />><xsl:value-of select="/Poi/Class/@g3" />
      </td>
     </tr>
     <tr>
      <td style="padding-left:15px;">
       电话:<xsl:value-of select="/Poi/Tel/@v" />
      </td>
     </tr>
     <tr>
      <td style="padding-left:15px;">
       地址:<xsl:value-of select="/Poi/Add/@v" />
      </td>
     </tr>
     <tr>
      <td style="padding-left:15px;">
       行政区划:<xsl:value-of select="/Poi/Admin/@pro" />><xsl:value-of select="/Poi/Admin/@city" />><xsl:value-of select="/Poi/Admin/@dis" />
      </td>
     </tr>
     <tr>
      <td height="20px">
      </td>
     </tr>
    </table>

</td></tr>
   
   <!-- 描述信息 -->
   <tr><td bgcolor="#FFFFFF" style="padding:10px;line-height: 1.5;">
   描述: <xsl:value-of select="/Poi/ExDes/@v" />
   </td></tr>

 </table>
</xsl:template>

</xsl:stylesheet>


如果你想用 LInux运行 CPRun.sh

export PATH=$PATH:/usr/local/jdk/bin
export PATH=$PATH:/usr/java/j2sdk1.4.2_09/bin
export CLASSPATH=$CLASSPATH:/var/www/html/51ditu_detail/CPDetailProgram
cd /var/www/html/51ditu_detail/CPDetailProgram
export LC_ALL=zh_CN.GBK
java -classpath $CLASSPATH/jdom.jar:$CLASSPATH/jaxen-1.1-beta-5.jar -Djava.awt.headless=true com.lingtu.cp.CpDetailOper CPConfig/CPConfig.xml
#echo MS:tar 172.16.73.138.tar.gz is start
#zip -r tar_172.16.73.138.zip /var/www/html/51ditu_detail/cmsDetailCreaHtmlProgram/Static/*>/dev/null
#echo MS:tar 172.16.73.138.zip is End
#scp tar_172.16.73.138.zip root@172.16.73.40:/var/www/html/51ditu_detail/StaticFileTarFromall/
#echo MS:172.16.73.138.tar.gz is copy to 172.16.73.40