用ROME来作:https://rome.dev.java.net/
自己的第一个项目IQBoree
里面要求有提供给客户Rss订阅的功能,找了下网上介绍,最后还是在rome的管网找到了解决方案
解决方案有两种:
1,写一个servlet,生成feed,直接由客户来订阅
2,写一个java.自动生成feed的xml文件,然后让客户通过读取这个xml文件来达到订阅Rss的目的
首先我就来讲解下第一种方法:
1.
FeedServlet.java
package com.iqboree.rss.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.iqboree.po.Article;
import com.iqboree.service.impl.ArticleManagerImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
/**
* @author Michael
*
*/
public class FeedServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(FeedServlet.class);
private static final String DEFAULT_FEED_TYPE = "default.feed.type";
private static final String FEED_TYPE = "type";
private static final String MIME_TYPE = "application/xml; charset=UTF-8";
private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
private static final DateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd");
private String _defaultFeedType;
List list;
public void init() {
_defaultFeedType = getServletConfig().getInitParameter(DEFAULT_FEED_TYPE);
_defaultFeedType = (_defaultFeedType!=null) ? _defaultFeedType : "atom_0.3";
log.info("初始化完成");//用来调试,可以看出在tomcat里的输出信息,自己可以去掉,后面的log.info() 也是同样的效果.
DATE_PARSER.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));//这里用来设置时区
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
try {
log.info("doget方法完成");
SyndFeed feed = getFeed(req);
String feedType = req.getParameter(FEED_TYPE);
feedType = (feedType!=null) ? feedType : _defaultFeedType;
feed.setFeedType(feedType);
res.setContentType(MIME_TYPE);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed,res.getWriter());
}
catch (FeedException ex) {
String msg = COULD_NOT_GENERATE_FEED_ERROR;
log(msg,ex);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
}
}
protected SyndFeed getFeed(HttpServletRequest req) throws IOException,FeedException {
log.info("Synd方法开始");
SyndFeed feed = new SyndFeedImpl();
feed.setTitle("Sample Feed (created with ROME)");//channle name ;display as the title
feed.setLink("http://rome.dev.java.net");
feed.setDescription("This feed has been created using ROME (Java syndication utilities");
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
List list = new ArrayList();
//项目是基于spring+webwork+hibernate的,但是在这里不知道让为这个servlet自动获得对应的DAO,所以只能用jdbc手动获取
String sql = "";
try {
log.info("开始进行jdbc操作");
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/iqboree";
Connection conn = DriverManager.getConnection(url,"root","ahuango");
if(conn == null)
{
log.info("conn NULL");
}
Statement stmt = conn.createStatement();
if(stmt==null)
{
log.info("NULLNULLNULL");
}
log.info("开始进行sql操作");
sql = "Select id,AddedDate,AddedBy,Title,Abstract,Body,CommentsEnabled,ViewCount," +
"ReleaseDate,ExpireDate,Approved,Listed,OnlyForMembers,Category_ID from iq_article";
ResultSet rs = stmt.executeQuery(sql);
log.info("begin iterator resultSet");
while(rs.next())
{
log.info("test 1");
Article art = new Article();
art.setId(Long.valueOf(rs.getString(1)));
log.info("test 2");
art.setAddedDate(rs.getDate(2));
log.info("test 3");
art.setAddedBy(rs.getString(3));
log.info("test 4");
art.setTitle(rs.getString(4));
log.info("test 5");
art.setAbstracts(rs.getString(5));
log.info("test 6");
art.setBody(rs.getString(6));
log.info("test 7");
art.setCommentsEnabled(Boolean.valueOf(rs.getBoolean(7)));
log.info("test 8");
art.setViewCount(Integer.valueOf(rs.getString(8)));
log.info("test 9");
art.setReleaseDate(rs.getDate(9));
log.info("test 10");
art.setExpireDate(rs.getDate(10));
log.info("test 11");
art.setApproved(Boolean.valueOf(rs.getBoolean(11)));
log.info("test 12");
art.setListed(Boolean.valueOf(rs.getBoolean(12)));
log.info("test 13");
art.setOnlyForMembers(Boolean.valueOf(rs.getBoolean(13)));
log.info("test 14");
// art.getCategory().setId(Long.valueOf(rs.getString(14)));
log.info("test 15");
list.add(art);
}
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
log.error("sql:"+sql+" "+e.toString());
}
//数据库信息获取完毕,里面的信息大家根据实际需要自己更改.
log.info("开始获取db");
//List articles=new ArticleManagerImpl().getCurrentNArticles(2);
log.info("开始迭代");
Iterator its = list.iterator();
log.info("开始添加feed条目");
while(its.hasNext())
{
Article art=(Article)its.next();
log.info("在while内部");
entry = new SyndEntryImpl();
entry.setTitle("\""+art.getTitle()+"\"");
entry.setLink("Link is:"+art.getId()+"\"");
try {
entry.setPublishedDate(DATE_PARSER.parse("2004-06-08"));
}
catch (ParseException ex) {
// IT CANNOT HAPPEN WITH THIS SAMPLE
}
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("The value is here:"+art.getTitle()); //set the content of this feed
entry.setDescription(description);
entries.add(entry);
}
feed.setEntries(entries);
return feed;
}
}
然后在web.xml中配置这个Rss的订阅地址
The web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>ROME Samples</display-name>
<servlet>
<servlet-name>FeedServlet</servlet-name>
<servlet-class>com.sun.syndication.samples.servlet.FeedServlet</servlet-class>
<init-param>
<param-name>default.feed.type</param-name>
<param-value>rss_2.0</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FeedServlet</servlet-name>
<url-pattern>/feed</url-pattern>
ervlet-mapping>
</web-app>
我的项目名称为IQBoree,所以这个feed相应的订阅地址为:http://localhost:8080/IQBoree/feed
2,自己生成一个xml文件,然后让客户来读取这个xml文件
生成xml文件:
if (true) {
try {
String feedType = "rss_1.0";
String fileName = "rssTest2.xml";
DateFormat dateParser = new SimpleDateFormat(DATE_FORMAT);
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(feedType);
feed.setTitle("Sample Feed (created with Rome)");
feed.setLink("http://rome.dev.java.net/");
feed.setDescription("This feed has been created using Rome (Java syndication utilities");
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
entry = new SyndEntryImpl();
entry.setTitle("Rome v1.0");
entry.setLink("http://wiki.java.net/bin/view/Javawsxml/Rome01");
entry.setPublishedDate(dateParser.parse("2006-11-16"));
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("Initial release of Rome");
entry.setDescription(description);
entries.add(entry);
//以上九行可以用来添加一条feed,可以更具自己的需要多添加几个,或者和第一种生成servlet的方法一样来从数据库读取
feed.setEntries(entries);
Writer writer = new FileWriter(fileName);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed,writer);
writer.close();
System.out.println("The feed has been written to the file ["+fileName+"]");
ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
}
使用rom读取rssUrl
把jdom和rom包拷贝到lib目录下。
直接在jsp页面上嵌入如下代码:
<%@ page language="java"
import="java.util.*;
import java.net.URL;
import java.io.InputStreamReader;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
" pageEncoding="UTF-8"%>
<%
try {
URL feedUrl = new URL("http://www.blogjava.net/crazycy/CommentsRSS.aspx");
//上面是那个需要读取的xml文件的存放地址,我这里找的是偶大哥的blog地址.
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
// System.out.println(feed);
out.println(feed);
// ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
%>
=============================================================================================
使用javaBean:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page import="com.sun.syndication.feed.synd.SyndFeed" %>
<%@ page import="com.sun.syndication.io.SyndFeedInput"%>
<%@ page import="com.sun.syndication.io.XmlReader"%>
<%@page import="java.net.*"%>
<%@page import="java.util.Properties"%>
<%@ page import="com.sun.syndication.feed.atom.Feed" %>
<%@ page import="java.util.List" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sina News</title>
</head>
<body>
<%
System.out.println("Start...");
String str ="http://www.blogjava.net/LittleRain/category/15573.html/rss";
Properties prop = System.getProperties();
// prop.put("http.proxyHost","10.10.10.11"); //这里填写代理的ip
//prop.put("http.proxyPort","8080");
boolean ok = false;
try {
URL feedUrl = new URL(str);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
out.println("Author:"+feed.getAuthor()+"<br>");
out.println("Title:"+feed.getTitle()+"<br>");
out.println("Description:"+feed.getDescription()+"<br>");
java.util.List list=feed.getEntries();
for (int i=0; i< list.size(); i++) {
com.sun.syndication.feed.synd.SyndEntry entry = (com.sun.syndication.feed.synd.SyndEntry)list.get(i);
//out.println(feed.get);
out.println(i+1+":");
out.println("<a href="+entry.getLink()+">"+entry.getTitle()+"</a>");
out.println(entry.getPublishedDate()+"<br>");
}
ok = true;
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
if (!ok) {
System.out.println();
out.println("FeedReader reads and prints any RSS/Atom feed type.");
out.println("The first parameter must be the URL of the feed to read.");
System.out.println();
}
%>
</body>
</html>