Spring rss实例
从spring 3 开始可以使用内置的方法来实现实现rss或者atom
org.springframework.web.servlet.view.feed.AbstractRssFeedView
org.springframework.web.servlet.view.feed.AbstractAtomFeedView
本实例使用org.springframework.web.servlet.view.feed.AbstractRssFeedView来实现rss
步骤
1:加入相关jar包
加入rome-x.jar和jdom.jar
2:加入视图解析(这里使用BeanNameViewResolver,此resolver的原理是返回的viewName和spring的context里面的name相同),如果有多个resolver需要设置order
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="0"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp">
<property name="order" value="1"/>
</bean>
3:实现RssView,继承自AbstractRssFeedView
@Component("rssView")//这个地方的配置要和后面controller的viewName一样
public class RssView extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String,Object> model, Channel feed,
HttpServletRequest request) {
String feedTitle = (String)model.get("feedTitle");
String feedDesc = (String)model.get("feedDesc");
String feedLink = (String)model.get("feedLink");
feed.setTitle(feedTitle);
feed.setDescription(feedDesc);
feed.setLink(feedLink);
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
@SuppressWarnings("unchecked")
List<RssItem> rssItems = (List<RssItem>) model.get("rssItemList");
List<Item> feedItems = new ArrayList<Item>();
for (RssItem rssItem : rssItems) {
Item feedItem = new Item();
feedItem.setTitle(rssItem.getTitle());
feedItem.setAuthor(rssItem.getAuthor());
feedItem.setPubDate(rssItem.getDatePublished());
Description desc = new Description();
desc.setValue(rssItem.getDescription());
feedItem.setDescription(desc);
feedItem.setLink(rssItem.getLink());
feedItems.add(feedItem);
}
return feedItems;
}
}
4 Controller
@Controller
@RequestMapping(value = "rss")
public class RssMgr {
@RequestMapping(value = "test_rss.htm")
public String testRss(Model model) {
List<RssItem> rssItems = new ArrayList<RssItem>();
for (int i = 0; i < 5; i++) {
RssItem n = new RssItem();
n.setTitle("第【"+i+"】条spring Rss测试消息标题");
n.setDescription("第【"+i+"】测试消息内容说明");
n.setLink("http://localhost:8080/springdemo/someurl.html");
n.setAuthor("作者:疯狂");
n.setDatePublished(new Date());
rssItems.add(n);
}
model.addAttribute("rssItemList", rssItems);
// 频道的相关信息
model.addAttribute("feedTitle", "spring RSS 测试");
model.addAttribute("feedDesc", "spring RSS 测试头条新闻");
model.addAttribute("feedLink",
http://localhost:8080/springdemo/rss/test_rss.htm);
return "rssView";
}
}
访问:http://localhost:8080/springdemo/rss/test_rss.htm
返回:
摘自 疯狂
补充:软件开发 , Java ,