• 当前位置: 首 页 > 教育百科 > 学历/技能 > 正文

    java在tomcat里实现计划任务定时生成SiteMap

    :2019年12月12日
    本站

    站想要让搜索引擎搜到,必须设置好keywords,description,title,做好SEO优化,同时sitemap.xml也是不可缺少的通过Google,得到一些帮助,把自己做的整理一下:第一、对文件进行查找:  &nbs...

    站想要让搜索引擎搜到,必须设置好keywords,description,title,做好SEO优化,同时sitemap.xml也是不可缺少的
    通过Google,得到一些帮助,把自己做的整理一下:
    第一、对文件进行查找:
     
        public class FileDemo {
          File myDir;
          File[] contents;
          List fileList;
          Iterator currentFileIt;
          File currentFile;
          String path;
         
          /**
           * 无参的构造函数
           * */
          public FileDemo() {
            path = new String("");
            fileList = new ArrayList();
          }
         
          /**
           * 有参的构造函数
           * */
          public FileDemo(String path) {
            this.path = path;
            fileList = new ArrayList();
          }
         
          /**
           * 设置要查看的文件路径
           */
          public void setPath(String path) {
            this.path = path;
          }
         
          /***************************************************************************
           * 返回当前目录的路径
           */
          public String getDirectory() {
            return myDir.getPath();
          }
         
          public void refreshList() {
            if (this.path.equals(""))
              path = "c:\\";
            myDir = new File(path);
         
            fileList.clear();
            contents = myDir.listFiles();
            // 重新装入路径下文件
            for (int i = 0; i < contents.length; i++) {
              fileList.add(contents[i]);
            }
            currentFileIt = fileList.iterator();
          }
         
          /**
           * 指到下一个条目
           */
          public boolean nextFile() {
            while (currentFileIt.hasNext()) {
              currentFile = (File) currentFileIt.next();
              
              return true;
            }
            return false;
          }
         
          /**
           * 返回当前指向的文件对象的文件名称
           */
          public String getFileName() {
            return currentFile.getName();
          }
         
          /**
           * 返回当前指向的文件对象的文件尺寸
           */
          public String getFileSize() {
            return convertFileSize(currentFile.length());
          }
         
          /**
           * 转换文件尺寸为指定格式。
           */
          private String convertFileSize(long size) {
            int divisor = 1;
            String unit = "bytes";
            if (size >= 1024 * 1024) {
              divisor = 1024 * 1024;
              unit = "MB";
            } else if (size >= 1024) {
              divisor = 1024;
              unit = "KB";
            }
            if (divisor == 1)
              return size / divisor + " " + unit;
            String aftercomma = "" + 100 * (size % divisor) / divisor;
            if (aftercomma.length() == 1)
              aftercomma = "0" + aftercomma;
            return size / divisor + "." + aftercomma + " " + unit;
          }
         
          /**
           * 返回文件的最后修改日期
           */
          public String getFileTimeStamp() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(new Date(currentFile.lastModified()));
         
            return dateString;
          }
         
          /**
           * 返回文件是不是一个目录
           */
          public boolean isDirectory() {
            return currentFile.isDirectory();
          }
         
        }
     
    第二、创建一个任务类,继承TimerTask
        public class XMLParese extends TimerTask{
          
          private ServletContext context;
          
          public XMLParese(ServletContext context){
            this.context=context;
          }
          
          @Override
          public void run() {
            // TODO Auto-generated method stub
            createSiteMap();
            
          }
          public void createSiteMap() {
         
            String priority = "0.75";// 级 别
            String changefreq = "daily";// "weekly";//频 率
            String xmlpath = "e:/sitemap.xml";// sitemap名称以及位置    
            String homeurl = "http://www.jsedu114.com"; // 栏目首页
            String []directory={"promotion","news","brand","goods","services","shop","winelive"};
            FileDemo fp = new FileDemo();
            try {
              Document document = DocumentHelper.createDocument();
              Element urlsetElement = document.addElement("urlset");
              urlsetElement.addAttribute("xmlns ",
                  "http://www.sitemaps.org/schemas/sitemap/0.9"); // "xmlns
                                          // "必须要有空格,否则会报错
              urlsetElement.addAttribute("xmlns",
                  "http://www.sitemaps.org/schemas/sitemap/0.9");
         
              urlsetElement.addAttribute("xmlns:xsi",
                  "http://www.w3.org/2001/XMLSchema-instance");
         
              urlsetElement.addAttribute("xsi:schemaLocation",
                  "http://www.sitemaps.org/schemas/sitemap/0.9 " +
         
                  "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
              
              //创建url根元素
              Element urlElement ;
              //为url根元素创建loc网页地址,lastmod更新时间,changefreq更改频率和priority级别
              Element locElement ;
              Element lastmodElement;
              Element changefreqElement;
              Element priorityElement;
              fp.setPath("D:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\ROOT\\");
              fp.refreshList();
              while (fp.nextFile()) {
                if (!fp.isDirectory()) {
                  homeurl="http://www.jsedu114.com/";
                  String f=fp.getFileName();
                  String fname=f.substring(f.lastIndexOf("."));
                  if((fname.equals(".html")||fname.equals(".htm")) && !f.equals("login.html")){
                    urlElement = urlsetElement.addElement("url");
                    locElement = urlElement.addElement("loc");
                    lastmodElement = urlElement.addElement("lastmod");
                    changefreqElement = urlElement.addElement("changefreq");
                    priorityElement = urlElement.addElement("priority");
                    
                    //导航赋值
                    homeurl = homeurl + fp.getFileName();
                    locElement.setText(homeurl);
                    lastmodElement.setText(fp.getFileTimeStamp());// 这里时间是你更新时间,这里暂时统一
                    changefreqElement.setText(changefreq);
                    priorityElement.setText(priority);
                  }
                }
              }
              
                    //各个目录下的文件
              for(int i=0;i<directory.length;i++){
                fp.setPath("D:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\ROOT\\"+directory[i]+"\\");
                fp.refreshList();
                while (fp.nextFile()) {
                  homeurl="http://www.jsedu114.com/"+directory[i]+"/";              
                  urlElement = urlsetElement.addElement("url");
                  locElement = urlElement.addElement("loc");
                  lastmodElement = urlElement.addElement("lastmod");
                  changefreqElement = urlElement.addElement("changefreq");
                  priorityElement = urlElement.addElement("priority");              
                  
                  homeurl = homeurl + fp.getFileName();
                  locElement.setText(homeurl);
                  lastmodElement.setText(fp.getFileTimeStamp());// 这里时间是你更新时间,这里暂时统一
                  changefreqElement.setText(changefreq);
                  priorityElement.setText(priority);
                }
              }
         
              XMLWriter writer = new XMLWriter(new FileOutputStream(new File(
                  xmlpath)));
              writer.write(document);
              writer.close();
              document = null;
              // 格式化
              formatXMLFile(xmlpath, "UTF-8");
            } catch (Exception ex) {
              ex.printStackTrace();
         
            }
         
          }
         
          /**
           * 格式化XML文档,并解决中文问题
           * @param xmlpath:xml文件路径
           * @param charSet:格式化的字符集
           * @return
           */
          public static boolean formatXMLFile(String xmlpath, String charSet) {
         
            boolean returnValue = false;
            try {
         
              SAXReader saxReader = new SAXReader();
              Document document = saxReader.read(new File(xmlpath));
              XMLWriter output = null;
              OutputFormat format = OutputFormat.createPrettyPrint();
              format.setEncoding(charSet);
              output = new XMLWriter(new FileWriter(new File(xmlpath)), format);
              output.write(document);
              output.close();
              document = null;
              saxReader = null;
              returnValue = true;
            } catch (Exception ex) {
              ex.printStackTrace();
            }
            return returnValue;
          }
         
        }
     
     第三、创建一个任务监听类,实现ServletContextListener 接口
     
        public class TimerListener implements ServletContextListener {
          // 设置启动时间为23点;
          private static final int hours = 23;
          private static final int minutes = 0;
          private static final int seconds = 0;
          private Timer timer = null;
         
          public void contextDestroyed(ServletContextEvent event) {
            timer.cancel();
            event.getServletContext().log("定时器销毁");
          }
         
          public void contextInitialized(ServletContextEvent event) {
                timer=new Timer(true);
                event.getServletContext().log("定时器已启动");
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, hours);
                calendar.set(Calendar.MINUTE, minutes);
                calendar.set(Calendar.SECOND, seconds);
                
                //SiteMap生成
                //间隔时间1天生成一次
                timer.schedule(new XMLParese(event.getServletContext()),calendar.getTime(),
                    1*24*60*60*1000);
          }
        }
     
    第四、在web中添加一个监听器
           web.xml里的配置
     
    <!-- 定时器 -->
    <listener>
      <listener-class>timer.TimerListener</listener-class>
    </listener>

    [编辑:宋聪乔 &发表于江苏]
    [我要纠错]

    来源:本文内容搜集或转自各大网络平台,并已注明来源、出处,如果转载侵犯您的版权或非授权发布,请联系小编,我们会及时审核处理。
    声明:江苏教育黄页对文中观点保持中立,对所包含内容的准确性、可靠性或者完整性不提供任何明示或暗示的保证,不对文章观点负责,仅作分享之用,文章版权及插图属于原作者。

    关键词: 想要 搜索引擎 必须 设置 keywords
    有价值
    0
    无价值
    0
    猜您喜欢
    最热文章

    暂不支持手机端,请登录电脑端访问

    正在加载验证码......

    请先完成验证