java 定时器生成sitemap.xml

来源:互联网 发布:手机版windows桌面主题 编辑:程序博客网 时间:2024/04/24 00:53

公司的网站需要做SEO优化,需要生成sitemap.xml文件,我的思路使用java内置定时器,每24小时生成一次,关于url地址,考虑到使用分布式框架实现比较麻烦,就使用配置property文件的方式,获取需要的url,由于项目中使用ssh框架,一时不知道如何配置连接,最后使用原始的jdbc实现了,因为 只需要连接和创建时间,不需要封装对象,很容易实现了!

步骤:

1.配置web.xml

<!-- 配置定时器listener  start -->
    <listener>
   <listener-class>
    cn.aresoft.timerListener.WebSitXmlTimerListener
   </listener-class>
</listener>
<!-- 配置定时器listener  end -->

2.定义定时器

package cn.aresoft.timerListener;


import java.util.Timer;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


public class WebSitXmlTimerListener implements ServletContextListener {
    private Timer timer;  
    private WebSitXmlTask task;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
System.out.println("定时器销毁");
}


@Override
public void contextInitialized(ServletContextEvent event) {
 timer = new java.util.Timer(true); 
         task = new WebSitXmlTask();
         System.out.println("定时器启动");  
         timer.schedule(task, 0, 24*60*60*1000);  
         System.out.println("已经添加任务调度表");  
}
}

3.定义定时器任务

  package cn.aresoft.timerListener;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimerTask;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


import cn.aresoft.logic.manager.customer.LoanService;


public  class WebSitXmlTask extends TimerTask{
private static Connection conn ;
static{
//获取数据连接
Map map = PropertiesUtil.read("jdbc");
String driver=(String) map.get("jdbc.driver");
String url=(String) map.get("jdbc.url");
String user=(String) map.get("jdbc.user");
String pwd=(String) map.get("jdbc.pwd");
try {
Class.forName(driver);
conn= DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private LoanService loanService;
public LoanService getLoanService() {
return loanService;
}
public void setLoanService(LoanService loanService) {
this.loanService = loanService;
}
@Override
public void run() {
Map map = PropertiesUtil.read("webSitXmlUrl");
String  staticUrl = (String) map.get("url.static");
String  dynamicUrl1 = (String) map.get("url.dynamic1");
String  dynamicUrl2= (String) map.get("url.dynamic2");
try {
createApplicationConfigXML(staticUrl,dynamicUrl1,dynamicUrl2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }  
private  String getSubStr(String str, int num) {
  String result = "";
  int i = 0;
  
  while(i < num) {
   int lastFirst = str.lastIndexOf('/');
   str = str.substring(0, lastFirst);
   i++;
  }
  return str;
 }


    public void createApplicationConfigXML(String staticUrl, String dynamicUrl1, String dynamicUrl2) throws SQLException{  
        //建立document对象  
        try {  
            Date now =new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String currentTime= sdf.format(now);
                Document document = DocumentHelper.createDocument();
                //添加文档根  
                Element root = document.addElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");
                /*添加静态标签*/
                String[] staticUrls = staticUrl.split("#");
                //循环添加标签
                for (String str : staticUrls) {
Element urlroot = root.addElement("url");
urlroot.addElement("loc").addText(str);
urlroot.addElement("lastmod").addText(currentTime);
urlroot.addElement("changefreq").addText("daily");
urlroot.addElement("priority").addText("0.4");
}
                /*添加动态标签*/
                //一个参数
                String[] dynamicUrls = dynamicUrl1.split("#");
                  for (String str : dynamicUrls) {
//截取参数名
                   String substring = str.substring(str.indexOf('?')+1, str.length());
                   String url = str.substring(0, str.indexOf('?'));
                   if("loanId".equals(substring)){
                   addLoanLevel(root,url);
                   }else if("debtId".equals(substring)){
                   addDebtLevel(root,url);
                   }
}
                 //两个参数
                  String[] dynamicUrls2 = dynamicUrl2.split("#");
                //截取参数名
               
                  for (String str : dynamicUrls2) {
                   String substring = str.substring(str.indexOf('?')+1, str.length());
                   String url = str.substring(0, str.indexOf('?'));
                   String[] strs = substring.split("&");
                   if("articleId".equals(strs[0])&&"columnId".equals(strs[1])){
                   addArticleLevel(root,strs,url);
                   }
}
                // 输出全部原始数据,并用它生成新的我们需要的XML文件 
                OutputFormat format = OutputFormat.createPrettyPrint();  
                format.setEncoding("utf-8");//根据需要设置编码  
                String u=this.getClass().getResource("/").getPath();
                String path = getSubStr(u, 3);
                String realPath=path.substring(1, path.length());
                File file=new File(realPath,"Sitemap.xml");
                XMLWriter writer = new XMLWriter(new FileWriter(file), format); 
                writer.write(document); //输出到文件  
                writer.close();
       } catch (UnsupportedEncodingException e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       } catch ( IOException e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       }  
   }
private void addArticleLevel(Element root, String[] strs, String url) {
try {
Statement statement = conn.createStatement();

String sql="";
if("http://www.rrdai.com/article/websiteNoticeContent.htm".equals(url)){
sql="select *  from tam_article t1, TAM_COLUMN t2, TAM_COLUMNARTICLE t3  where t3.tam_column_id = t2.id and t3.tam_article_id = t1.id  and t2.id = 101";


}else if("https://www.rrdai.com/article/mtbgContent.htm".equals(url)){
sql="select *  from tam_article t1, TAM_COLUMN t2, TAM_COLUMNARTICLE t3  where t3.tam_column_id = t2.id and t3.tam_article_id = t1.id  and t2.id = 102";

}else if("http://www.rrdai.com/article/tradeNewsContent.htm".equals(url)){

sql="select *  from tam_article t1, TAM_COLUMN t2, TAM_COLUMNARTICLE t3  where t3.tam_column_id = t2.id and t3.tam_article_id = t1.id  and t2.id = 243";
}

ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int id = resultSet.getInt("id");
String date = resultSet.getString("TIME_CREATE");
addArticle(id,root,strs,date,url);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void addArticle(int id, Element root, String[] strs, String date, String url) {


try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1=sdf.parse(date);
String date2=sdf2.format(date1);
Element urlroot = root.addElement("url");
if("http://www.rrdai.com/article/websiteNoticeContent.htm".equals(url)){
urlroot.addElement("loc").addText(url+"?articleId="+id+"&"+"columnId=101");
}else if("https://www.rrdai.com/article/mtbgContent.htm".equals(url)){
urlroot.addElement("loc").addText(url+"?articleId="+id+"&"+"columnId=102");

}else if("http://www.rrdai.com/article/tradeNewsContent.htm".equals(url)){
urlroot.addElement("loc").addText(url+"?articleId="+id+"&"+"columnId=243");
}
urlroot.addElement("lastmod").addText(date2);
urlroot.addElement("changefreq").addText("daily");
urlroot.addElement("priority").addText("0.4");
} catch (ParseException e) {
e.printStackTrace();
}


}
private void addDebtLevel(Element root, String url) {
try {
Statement statement = conn.createStatement();
String sql="select * from  tcustomer_creditor";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int id = resultSet.getInt("id");
String date = resultSet.getString("CREATE_TIME");
addDebt(id,date,root,url);
}
} catch (SQLException e) {
e.printStackTrace();
}
}

private void addLoanLevel(Element root, String url) throws SQLException {
 
Statement statement = conn.createStatement();
String sql="select * from  tcustomer_loan";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int id = resultSet.getInt("id");
String date = resultSet.getString("TIME_CREATE");
addLoan(id,date,root,url);
}
 
}
private void addLoan(int id, String date, Element root, String url) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1=sdf.parse(date);
String date2=sdf2.format(date1);
Element urlroot = root.addElement("url");
urlroot.addElement("loc").addText(url+"?loanId="+id);
urlroot.addElement("lastmod").addText(date2);
urlroot.addElement("changefreq").addText("daily");
urlroot.addElement("priority").addText("0.4");
} catch (ParseException e) {
e.printStackTrace();
}
}  
private void addDebt(int id, String date, Element root, String url) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1=sdf.parse(date);
String date2=sdf2.format(date1);
Element urlroot = root.addElement("url");
urlroot.addElement("loc").addText(url+"?debtId="+id);
urlroot.addElement("lastmod").addText(date2);
urlroot.addElement("changefreq").addText("daily");
urlroot.addElement("priority").addText("0.4");
} catch (ParseException e) {
e.printStackTrace();
}
}
}

4.property文件

url.static=http://www.rrdai.com#http://www.rrdai.com/customer/login.htm#http://www.rrdai.com/customer/register.htm#http://www.rrdai.com/help/helpSelectMenu.htm?parameter=%25E5%25B8%25B8%25E8%25A7%2581%25E9%2597%25AE%25E9%25A2%2598,%25E5%25B8%25B8%25E8%25A7%2581%25E9%2597%25AE%25E9%25A2%2598#http://www.rrdai.com/help/debt.htm?parameter=%25E5%2580%25BA%25E6%259D%2583%25E8%25BD%25AC%25E8%25AE%25A9,%25E5%2580%25BA%25E6%259D%2583%25E8%25BD%25AC%25E8%25AE%25A9&columnId=222#http://www.rrdai.com/help/arpAndCost.htm?parameter=%25E5%2588%25A9%25E7%258E%2587%25E5%2592%258C%25E8%25B4%25B9%25E7%2594%25A8,%25E5%2588%25A9%25E7%258E%2587%25E5%2592%258C%25E8%25B4%25B9%25E7%2594%25A8&columnId=#http://www.rrdai.com/help/moneySafty.htm?parameter=%25E6%259C%25AC%25E9%2587%2591%25E4%25BF%259D%25E9%259A%259C,%25E6%259C%25AC%25E9%2587%2591%25E4%25BF%259D%25E9%259A%259C&columnId=223#http://www.rrdai.com/help/glossary.htm?parameter=%25E5%2590%258D%25E8%25AF%258D%25E8%25A7%25A3%25E9%2587%258A,%25E5%2590%258D%25E8%25AF%258D%25E8%25A7%25A3%25E9%2587%258A&columnId=#http://www.rrdai.com/loan/loanListNew.htm#http://www.rrdai.com/loan/custFastApp.htm#http://www.rrdai.com/index/aboutus.htm#http://www.rrdai.com/aqbz/goodBenefit.htm#http://www.rrdai.com/aqbz/saftyInsurance.htm#http://www.rrdai.com/aqbz/moving.htm#http://www.rrdai.com/index/maps.htm


url.dynamic1=http://www.rrdai.com/loan/loanInfoNew.htm?loanId#http://www.rrdai.com/customer/debtInfoNew.htm?debtId


url.dynamic2=http://www.rrdai.com/article/websiteNoticeContent.htm?articleId&columnId#http://www.rrdai.com/article/tradeNewsContent.htm?articleId&columnId#https://www.rrdai.com/article/mtbgContent.htm?articleId&columnId


0 0
原创粉丝点击