知識庫 / Spring / Spring MVC RSS 訂閱

使用 Spring MVC 顯示 RSS 源

Spring MVC
HongKong
6
01:44 PM · Dec 06 ,2025

1. 簡介

本快速教程將演示如何使用 Spring MVC 和 AbstractRssFeedView 類構建一個簡單的 RSS 訂閲源。

隨後,我們還將實現一個簡單的 REST API,以便通過網絡公開我們的訂閲源。

2. RSS 訂閲

在深入討論具體實現細節之前,我們先快速回顧一下 RSS 的概念及其工作原理。

RSS 是一種 Web 訂閲源,它允許用户輕鬆追蹤網站的更新。此外,RSS 訂閲源基於 XML 文件,對網站內容進行總結。新聞聚合器可以訂閲一個或多個訂閲源,並定期檢查 XML 文件是否發生變化,從而顯示更新內容。

3. 依賴項

首先,由於 Spring 的 RSS 支持基於 ROME 框架,我們需要將其作為依賴項添加到我們的 pom 中,才能實際使用它:

<dependency>
    <groupId>com.rometools</groupId>
    <artifactId>rome</artifactId>
    <version>1.10.0</version>
</dependency>

為了瞭解羅馬,請參考我們之前的文章。

4. 訂閲源實現

接下來,我們將構建實際的訂閲源。為此,我們將擴展 AbstractRssFeedView 類並實現其中兩個方法。

第一個方法將接收一個 Channel 對象作為輸入,並將其填充與訂閲源的元數據。

另一個方法將返回一個項目列表,該列表代表訂閲源的內容。

@Component
public class RssFeedView extends AbstractRssFeedView {

    @Override
    protected void buildFeedMetadata(Map<String, Object> model, 
      Channel feed, HttpServletRequest request) {
        feed.setTitle("Baeldung RSS Feed");
        feed.setDescription("Learn how to program in Java");
        feed.setLink("http://www.baeldung.com");
    }

    @Override
    protected List<Item> buildFeedItems(Map<String, Object> model, 
      HttpServletRequest request, HttpServletResponse response) {
        Item entryOne = new Item();
        entryOne.setTitle("JUnit 5 @Test Annotation");
        entryOne.setAuthor("[email protected]");
        entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
        entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
        return Arrays.asList(entryOne);
    }
}

5. 公告流的暴露

最後,我們將構建一個簡單的 REST 服務,以使我們的 feed 在 Web 上可用。該服務將返回我們剛剛創建的視圖對象:

@RestController
public class RssFeedController {

    @Autowired
    private RssFeedView view;
    
    @GetMapping("/rss")
    public View getFeed() {
        return view;
    }
}

由於我們使用 Spring Boot 啓動應用程序,因此我們將實現一個簡單的啓動類:

@SpringBootApplication
public class RssFeedApplication {
    public static void main(final String[] args) {
        SpringApplication.run(RssFeedApplication.class, args);
    }
}

在運行我們的應用程序後,當我們向我們的服務發送請求時,將會看到以下 RSS 訂閲源:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <channel>
        <title>Baeldung RSS Feed</title>
        <link>http://www.baeldung.com</link>
        <description>Learn how to program in Java</description>
        <item>
            <title>JUnit 5 @Test Annotation</title>
            <link>http://www.baeldung.com/junit-5-test-annotation</link>
            <pubDate>Tue, 19 Dec 2017 00:00:00 GMT</pubDate>
            <author>[email protected]</author>
        </item>
    </channel>
</rss>

6. 結論

本文介紹瞭如何使用 Spring 和 ROME 構建一個簡單的 RSS 源,並使其可通過 Web 服務供消費者使用。

在我們的示例中,我們使用了 Spring Boot 啓動應用程序。有關此主題的更多詳細信息,請繼續閲讀本文檔中關於 Spring Boot 的入門介紹。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.