`
pengjj2
  • 浏览: 139973 次
  • 性别: Icon_minigender_1
  • 来自: 无锡
社区版块
存档分类
最新评论

java读取rss源,jquery显示新闻

 
阅读更多

因为jquery的ajax有跨域问题,使用java来读取rss源,用jquery解析返回回来的xml文件并显示

1、html代码,tab页面样式

 <div class="adlike dcsbox">
      <div class="h">
        <h3>&nbsp;</h3>
        <a class="dcsbox-h-more" href="/templates/index.jsp" target="_blank">更多</a>
        <ul class="poptab" id="poptab1"></ul>
      </div>
      <div class="b" id="poptab1-c"></div>
      <div class="f"><b></b></div>
    </div>

2、jquery代码

<script type="text/javascript">
//tab插件
(function($){
  $.poptab=function(tabs,targets,num){
   var curtab=$('poptab'),curtarget=curtab,
   add=function(k,v,n){
    if(!k) return false
    k.each(function(i,o){
     $(o).mouseover(function(){
      curtab.removeClass("cur");
      curtab=$(o).addClass("cur");
      curtarget.hide();
      curtarget=v.eq(i).show();
      });
      if(n===i){
       $(o).mouseover();
       }
     });
   return add;
    };
  if(tabs){
   if(tabs.size()==0) return add;
   add(tabs,targets,num);
   if(num===undefined){
     tabs.eq(0).mouseover();
    }
   };
  return add;
   }
})(jQuery);
//jQuery.poptab(jQuery("#poptab1>li"),jQuery("#poptab1-c>div"),2)
(function($){
 var poptab=$.poptab($("#poptab1>li"),$("#poptab1-c>div"));
 //var poptab=$.poptab(),
 hasTumb=function(o){
  if(o.getElementsByTagName("description").length>0){
   return o.getElementsByTagName("description")[0].firstChild.data.match(/<img\s.*?src=.*?>/i);
   }
  },
 markrss=function(title,src,num){
      var tt,url="/static/downloadService?action=rssDown";
   if(src.indexOf("http://")<0) url=src;
   if(this instanceof $){
    tt=this;
    }else{
     tt=$("<li><span></span>"+title+"</li>").appendTo("#poptab1");
     };
   $.ajax({
   url:url,
   type:"POST",
   data:{url:src},
   dataType:"xml",
   success:function(m){
    var pho=null,//图片新闻
    photitle="",
    pholink="",
    head="",//标题新闻
    list=[],//新闻列表
    items=m.getElementsByTagName("item");
    for(var i=0,len=items.length;i<len;i++){
     if(pho==null){
      pho=hasTumb(items[i]);
      photitle=items[i].getElementsByTagName("title")[0].firstChild.data;
      pholink=items[i].getElementsByTagName("link")[0].firstChild.data;
      if(pho!=null){
       pho=unescape(pho.toString()).replace("http://t1.baidu.com/it/u=","").replace("&fm=30","");
       pho=pho.replace('src="images/','src="/templates/images/');
       continue;
       }
      };
     if(head==""){
      head='<a href="'+items[i].getElementsByTagName("link")[0].firstChild.data+'" class="p-news-head" target="_blank">'+items[i].getElementsByTagName("title")[0].firstChild.data+'</a>';
      continue;
      };
     if(list.length<5){
      list.push('<li><a href="'+items[i].getElementsByTagName("link")[0].firstChild.data+'" target="_blank">'+items[i].getElementsByTagName("title")[0].firstChild.data+'</a></li>');
      }
     };
     tt.find("span").remove();
        poptab(tt,
     $('<div class="p-news" style="display:none">\
          <div class="p-news-pho">\
            <a class="p-news-pho-img" href="'+pholink+'" target="_blank">'+pho+'</a>\
            <a href="'+pholink+'" target="_blank"><span>'+photitle+'</span></a>\
          </div>\
          <div class="p-news-list">\
            '+head+'\
            <ul>\
              '+list.join("")+'\
            </ul>\
          </div>\
        </div>').appendTo("#poptab1-c").find("img").bind("load",function(){
   var w=this.width,h=this.height,_w=145,_h=131;
   if(w==0){
    var t=this,f=arguments.callee,
    fixIE=function(){
     tt.unbind("mouseover",fixIE)
     f.apply(t);
     };
    tt.bind("mouseover",fixIE);
    return false;
    }
   if(w/h>_w/_h){
    this.style.height=_h+"px";
    this.style.width=_h*w/h+"px";
    this.style.marginLeft="-"+(_h*w/h-_w)/2+"px";
    }else{
     this.style.width=_w+"px";
     this.style.height=_w*h/w+"px";
     this.style.marginTop="-"+(_w*h/w-_h)/2+"px";
     };
   }).end(),num);
    },
   error:function(){
    tt.find("span").remove();
    $("<a href='#'>刷新</a>").click(function(){
     markrss.apply(tt,[title,src,num]);
     $(this).remove();
     tt.prepend("<span/>");
     return false;
     }).appendTo(tt);
    }
   });
  };
 //rss来源:http://www.baidu.com/search/rss.html#02
 //markrss("新闻","/templates/cnrss.xml",0);//公司
 markrss("公告","/templates/ggrss.xml",0);//公告
 //markrss("行业","/templates/hyrss.xml");//行业
 
 markrss("热点","http://news.baidu.com/n?cmd=1&class=civilnews&tn=rss");
 markrss("国际","http://news.baidu.com/n?cmd=1&class=internews&tn=rss");
 markrss("财经","http://news.baidu.com/n?cmd=1&class=finannews&tn=rss");
 markrss("社会","http://news.baidu.com/n?cmd=1&class=socianews&tn=rss");
})(jQuery);
</script>

这里用的是百度的源

3、servlet读取源信息

response.setContentType("text/xml;charset=utf-8");
             System.out.println("rss");
             String url = request.getParameter("url");
             System.out.println(url);
             StringBuffer content = new StringBuffer();
             String line = "";
             String xml = "";
             Element el = null;
             //先从缓存中获取
             Cache rssCache = MyEcache.getCache("rsscache");
          el = rssCache.get(url);
          if(el!=null)
          {
           xml = (String) el.getObjectValue();
           if(xml!=null && !"".equals(xml) && !xml.contains("访问出错"))
           {
            response.getWriter().print(xml);
                  response.getWriter().flush();
                  response.getWriter().close();
                  return;
           }
          }
             URL ser = new URL(url);
             HttpURLConnection con = (HttpURLConnection) ser.openConnection();
             //con.connect();
             InputStream in = con.getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(in,"gb2312"));
             while((line=br.readLine())!=null)
             {
              content.append(line);
             }
             in.close();
             con.disconnect();
             xml = content.toString();
             //byte[] b = cc.getBytes("UTF-8");
             //String xml = new String(b, 0, b.length, "UTF-8");
//             Document doc = DocumentHelper.parseText(xml);
//             System.out.println("(2)"+xml);
             xml = xml.replace("gb2312", "UTF-8");
             el = new Element(url, xml);
                rssCache.putQuiet(el);
             response.getWriter().print(xml);
             response.getWriter().flush();
             response.getWriter().close();

注:百度的rss源会判断你是否机器读取,如果你不停的链接它的话,会屏蔽你哦,使用采用ehcache做个缓存,5分钟,或者半个小时读取一次,就可以解决这个问题

分享到:
评论

相关推荐

    java代码-使用java解决RSS阅读器的问题的源代码

    java代码-使用java解决RSS阅读器的问题的源代码 ——学习参考资料:仅用于个人学习使用!

    java读取PDF显示于浏览器

    Java读取PDF并显示在浏览器是一项常见的技术需求,特别是在Web应用中,用户可能需要预览或下载PDF文档。为了实现这一功能,我们需要了解几个关键知识点: 1. **PDF阅读器集成**:描述中提到的前提是本地电脑需要...

    java实现rss的发布和订阅

    RSSJava提供了一组API来创建、读取和写入RSS feeds,而Rome则是一个更全面的库,支持RSS和Atom格式,包含了解析、生成和订阅功能。 7. **RSS更新通知**: 虽然RSS本身不提供更新通知机制,但可以通过结合Webhooks...

    Java读取Excel内容

    Java读取Excel内容 v Java读取Excel内容 Java读取Excel内容

    java读取raw格式的图片并显示

    在本场景中,我们将探讨如何使用Java Swing技术读取RAW格式的图片文件并将其显示在用户界面上。 首先,理解RAW文件的基本概念是至关重要的。RAW文件包含了相机传感器捕获的原始光数据,这些数据未经色彩校正、白...

    读取RSS-SAX解析XML实例(java版)

    在Java中,读取RSS数据首先需要获取RSS源的URL,然后使用XML解析器解析该URL的内容。这里采用的是SAX解析器,它通过触发一系列的事件(如开始文档、开始元素、结束元素等)来处理XML数据。以下是使用SAX解析XML的...

    java读取dwg的预览图

    java读取dwg的预览图, 使java将autocad 的dwg文件读出预览图

    java读取ShapeFile文件的源代码.pdf

    Java 读取 ShapeFile 文件的源代码解析 ShapeFile 是一种常用的 GIS 文件格式,用于存储地理空间数据。 Java 语言可以通过各种库和框架来读取 ShapeFile 文件。下面将对 Java 读取 ShapeFile 文件的源代码进行解析...

    java读取txt文件内容(java快速读取,程序已调试通)

    java读取txt文件,可以以文件路径构造这个流,:FileInputStream fin = new FileInputStream("d:/test.txt"); 然后使用这个流直接读取到文件,再使用reader构造BufferedReader,按行读取一整行的文本,作为字符串返回...

    java读取excel数据导入数据库源码

    java读取excel数据导入数据库源码 java读取excel数据导入数据库源码

    jquery读取excel组件

    jquery读取excel组件,可读取excel表格中的内容

    java读取图片文件流

    java读取本地图片文件获取流!java读取本地图片文件获取流!

    java从mdb中读取并显示数据

    在Java编程环境中,读取和显示来自mdb数据库(通常是Microsoft Access数据库)的数据是一个常见的任务,特别是在需要集成数据库功能的桌面应用程序中。以下是一篇详细解释如何实现这一目标的文章。 首先,要与mdb...

    rss源代码(在线阅读新闻)

    【标题】:“RSS源代码(在线阅读新闻)” 在IT领域,RSS(Really Simple Syndication)是一种用于发布和聚合Web内容的XML格式。它允许用户订阅感兴趣的网站或博客的更新,而无需亲自访问每个站点。RSS源代码通常指...

    Java读取TIFF文件

    本篇文章将深入探讨如何使用Java来读取TIFF文件,并获取其尺寸——即图像的宽度(长)和高度。 在Java中,处理TIFF文件通常需要借助第三方库,因为Java的标准API(如`java.awt.image.BufferedImage`)并不直接支持...

    java 读取PDF文件中的内容

    在Java编程环境中,读取PDF文件中的内容是一个常见的任务,特别是在处理文档自动化或者数据分析时。PDF(Portable Document Format)是一种跨平台的文件格式,用于精确地保留文档的格式和内容。下面将详细介绍如何...

    java 读取文件 文件读取操作

    在Java编程语言中,文件读取是常见的任务,可以用于处理各种类型的数据,如文本、图像、音频等。本文将详细介绍Java中四种不同的文件读取方法:按字节读取、按字符读取、按行读取以及随机读取。 1. **按字节读取...

    java读取*.mdb文件数据

    在Java中读取Access数据库的数据通常涉及使用Java Database Connectivity (JDBC) API。本文将详细介绍如何使用JDBC连接到Access数据库并进行分页读取数据,同时也会提及相关的库和示例代码。 首先,我们需要一个能...

    java读取grib2文件

    Java读取GRIB2文件是气象和气候数据处理中常见的任务,因为GRIB(General Regularly-distributed Information in Binary form)格式是世界气象组织(WMO)推荐的标准数据存储格式,广泛用于气象预报和气候模型输出。...

    Java读取Word表格内容

    通过Java读取word表格中的内容,将内容存到数据库中,将Word中的图片存到硬盘中

Global site tag (gtag.js) - Google Analytics