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分钟,或者半个小时读取一次,就可以解决这个问题

猜你喜欢

转载自pengjj2.iteye.com/blog/1255317
RSS
今日推荐