At the time of this writing, Spring 3.0 isn't out yet, but that doesn't mean we can't
start goofing around with the nightly snapshots.
I've been doing just that, and in this article I'll show you how to publish an RSS feed using the new AbstractRssFeedView
class from Spring 3.0.
Those familiar with Spring Modules might recognize our view class.
It began life as AbstractRssView
in the Spring Modules project. But as of Spring 3.0, it's now a
first-class member of the framework (though it's been renamed to AbstractRssFeedView
), along with the AbstractAtomFeedView
class for Atom feeds, and the AbstractFeedView
, which serves as a base class for both. The new classes,
like the old one, are based on Sun's ROME API.
You'll need to know Spring Web MVC to get the most out of this article. In particular, you'll need to understand the relationship between controllers and views, which in a nutshell is this: when a controller is done processing a request, it returns a logical view name that a view resolver subsequently maps to a view.
Without further ado, let's look at some code.
Let's start with the controller, since processing starts there, and since that's probably more familiar to more readers than implementing views. Listing 1 shows a pretty basic controller for a news feed.
package rssdemo.web; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Required; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import rssdemo.model.NewsItem; import rssdemo.service.NewsService; @Controller public final class NewsController { private NewsService newsService; private String rssNewsFeedView; @Required public void setNewsService(NewsService newsService) { this.newsService = newsService; } @Required public void setRssNewsFeedView(String rssNewsFeedView) { this.rssNewsFeedView = rssNewsFeedView; } @RequestMapping("/news.rss") public String rss(HttpServletResponse res, Model model) { List<NewsItem> newsItems = newsService.getAllNewsItems(); model.addAttribute(newsItems); // 1 return rssNewsFeedView; // 2 } }
As you can see, this controller really is as simple as I said it would be. Our rss()
method grabs a list
of NewsItem
s from the NewsService
1 and places it on the Model
under a conventionally-generated key, which in this case would be newsItemList
. Then we simply return an
injected logical view name 2, which we're going to map to an actual view shortly. (We
inject the view name to maintain the separation between the controller and the view.)
Now let's check out the star of the show, which would be our view.