Spring MVCでRSSフィードを表示する
1. 前書き
このクイックチュートリアルでは、Spring MVCとAbstractRssFeedViewクラスを使用して簡単なRSSフィードを作成する方法を示します。
その後、単純なREST APIも実装して、フィードをネットワーク上で公開します。
2. RSSフィード
実装の詳細に入る前に、RSSとは何か、そしてRSSがどのように機能するかについて簡単に確認しましょう。
RSSは、ユーザーがWebサイトからの更新を簡単に追跡できるWebフィードの一種です。 さらに、RSS feeds are based on an XML file which summarizes the content of a site.ニュースアグリゲーターは、1つ以上のフィードをサブスクライブし、XMLが変更されたかどうかを定期的にチェックすることで、更新を表示できます。
3. 依存関係
まず、実際に使用する前に、Spring’s RSS support is based on the ROME framework、we’ll need to add it as a dependencyをpom に変換します。
com.rometools
rome
1.10.0
ローマのガイドについては、previous articleをご覧ください。
4. フィードの実装
次に、実際のフィードを作成します。 それを行うために、we’ll extend the AbstractRssFeedView class and implement two of its methods.
最初のオブジェクトは、入力としてChannelオブジェクトを受け取り、フィードのメタデータを入力します。
The other will return a list of items which represents the feed’s content:
@Component
public class RssFeedView extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map model,
Channel feed, HttpServletRequest request) {
feed.setTitle("example RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.example.com");
}
@Override
protected List- buildFeedItems(Map
model,
HttpServletRequest request, HttpServletResponse response) {
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("[email protected]");
entryOne.setLink("http://www.example.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
return Arrays.asList(entryOne);
}
}
5. フィードの公開
最後に、make our feed available on the webへの単純なRESTサービスを構築します。 サービスは、作成したばかりのビューオブジェクトを返します。
@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フィードが表示されます。
example RSS Feed
http://www.example.com
Learn how to program in Java
-
JUnit 5 @Test Annotation
http://www.example.com/junit-5-test-annotation
Tue, 19 Dec 2017 00:00:00 GMT
[email protected]
6. 結論
この記事では、SpringとROMEを使用して簡単なRSSフィードを作成し、Webサービスを使用して消費者が利用できるようにする方法について説明しました。
この例では、Spring Bootを使用してアプリケーションを起動しました。 このトピックの詳細については、continue reading this introductory article on Spring Bootをご覧ください。
いつものように、使用されるすべてのコードは利用可能なover on GitHubです。