適用于Atom Feed的Spring MVC

如何僅使用兩個類就將提要(Atom)添加到Web應用程序?
Spring MVC呢?

這是我的假設:

  • 您正在使用Spring框架
  • 您有一些要發布在供稿中的實體,例如“新聞”
  • 您的“新聞”實體具有creationDate,title和shortDescription
  • 您有一些存儲庫/倉庫,例如“ NewsRepository”,它將從數據庫中返回新聞
  • 你想寫得盡可能少
  • 您不想手動格式化Atom(xml)

實際上,您實際上不需要在應用程序中使用Spring MVC。 如果這樣做,請跳至步驟3。

步驟1:將Spring MVC依賴項添加到您的應用程序

使用Maven將是:

<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.1.0.RELEASE</version>
</dependency>

步驟2:添加Spring MVC DispatcherServlet

使用web.xml將是:

<servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/feed</url-pattern>
</servlet-mapping>

注意,我將url-pattern設置為“ / feed”,這意味著我不希望Spring MVC處理我的應用程序中的任何其他URL(我在其余的應用程序中使用了不同的Web框架)。 我還給它提供了一個全新的contextConfigLocation,其中僅保留了mvc配置。

請記住,將DispatcherServlet添加到已經具有Spring的應用程序時(例如,從ContextLoaderListener繼承),您的上下文是從全局實例繼承的,因此您不應創建在該全局實例中再次存在的bean,也不應該包含定義它們的xml。 注意兩次Spring上下文,并查閱spring或servlet文檔以了解發生了什么。

步驟3.添加ROME –處理Atom格式的庫

與Maven是:

<dependency><groupId>net.java.dev.rome</groupId><artifactId>rome</artifactId><version>1.0.0</version>
</dependency>

步驟4.編寫非常簡單的控制器

@Controller
public class FeedController {static final String LAST_UPDATE_VIEW_KEY = 'lastUpdate';static final String NEWS_VIEW_KEY = 'news';private NewsRepository newsRepository;private String viewName;protected FeedController() {} //required by cglibpublic FeedController(NewsRepository newsRepository, String viewName) {notNull(newsRepository); hasText(viewName);this.newsRepository = newsRepository;this.viewName = viewName;}@RequestMapping(value = '/feed', method = RequestMethod.GET)        @Transactionalpublic ModelAndView feed() {ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName(viewName);List<News> news = newsRepository.fetchPublished();modelAndView.addObject(NEWS_VIEW_KEY, news);modelAndView.addObject(LAST_UPDATE_VIEW_KEY, getCreationDateOfTheLast(news));return modelAndView;}private Date getCreationDateOfTheLast(List<News> news) {if(news.size() > 0) {return news.get(0).getCreationDate();}return new Date(0);}
}

如果您想復制并粘貼(誰不想要),這里有一個測試:

@RunWith(MockitoJUnitRunner.class)
public class FeedControllerShould {@Mock private NewsRepository newsRepository;private Date FORMER_ENTRY_CREATION_DATE = new Date(1);private Date LATTER_ENTRY_CREATION_DATE = new Date(2);private ArrayList<News> newsList;private FeedController feedController;@Beforepublic void prepareNewsList() {News news1 = new News().title('title1').creationDate(FORMER_ENTRY_CREATION_DATE);News news2 = new News().title('title2').creationDate(LATTER_ENTRY_CREATION_DATE);newsList = newArrayList(news2, news1);}@Beforepublic void prepareFeedController() {feedController = new FeedController(newsRepository, 'viewName');}@Testpublic void returnViewWithNews() {//givengiven(newsRepository.fetchPublished()).willReturn(newsList);//whenModelAndView modelAndView = feedController.feed();//thenassertThat(modelAndView.getModel()).includes(entry(FeedController.NEWS_VIEW_KEY, newsList));}@Testpublic void returnViewWithLastUpdateTime() {//givengiven(newsRepository.fetchPublished()).willReturn(newsList);//whenModelAndView modelAndView = feedController.feed();//thenassertThat(modelAndView.getModel()).includes(entry(FeedController.LAST_UPDATE_VIEW_KEY, LATTER_ENTRY_CREATION_DATE));}@Testpublic void returnTheBeginningOfTimeAsLastUpdateInViewWhenListIsEmpty() {//givengiven(newsRepository.fetchPublished()).willReturn(new ArrayList<News>());//whenModelAndView modelAndView = feedController.feed();//thenassertThat(modelAndView.getModel()).includes(entry(FeedController.LAST_UPDATE_VIEW_KEY, new Date(0)));}
}

注意:在這里,我正在使用fest-assert和mockito。 依賴項是:

<dependency><groupId>org.easytesting</groupId><artifactId>fest-assert</artifactId><version>1.4</version><scope>test</scope>
</dependency>
<dependency><groupId>org.mockito</groupId><artifactId>mockito-all</artifactId><version>1.8.5</version><scope>test</scope>
</dependency>

步驟5.編寫非常簡單的視圖

這是所有魔術格式化發生的地方。 一定要看一看Entry類的所有方法,因為您可能想使用/填充很多東西。

import org.springframework.web.servlet.view.feed.AbstractAtomFeedView;
[...]public class AtomFeedView extends AbstractAtomFeedView {private String feedId = 'tag:yourFantastiSiteName';private String title = 'yourFantastiSiteName: news';private String newsAbsoluteUrl = 'http://yourfanstasticsiteUrl.com/news/'; @Overrideprotected void buildFeedMetadata(Map<String, Object> model, Feed feed, HttpServletRequest request) {feed.setId(feedId);feed.setTitle(title);setUpdatedIfNeeded(model, feed);}private void setUpdatedIfNeeded(Map<String, Object> model, Feed feed) {@SuppressWarnings('unchecked')Date lastUpdate = (Date)model.get(FeedController.LAST_UPDATE_VIEW_KEY);if (feed.getUpdated() == null || lastUpdate != null || lastUpdate.compareTo(feed.getUpdated()) > 0) {feed.setUpdated(lastUpdate);}}@Overrideprotected List<Entry> buildFeedEntries(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {@SuppressWarnings('unchecked')List<News> newsList = (List<News>)model.get(FeedController.NEWS_VIEW_KEY);List<Entry> entries = new ArrayList<Entry>();for (News news : newsList) {addEntry(entries, news);}return entries;}private void addEntry(List<Entry> entries, News news) {Entry entry = new Entry();entry.setId(feedId + ', ' + news.getId());entry.setTitle(news.getTitle());entry.setUpdated(news.getCreationDate());entry = setSummary(news, entry);entry = setLink(news, entry);entries.add(entry);}private Entry setSummary(News news, Entry entry) {Content summary = new Content();summary.setValue(news.getShortDescription());entry.setSummary(summary);return entry;}private Entry setLink(News news, Entry entry) {Link link = new Link();link.setType('text/html');link.setHref(newsAbsoluteUrl + news.getId()); //because I have a different controller to show news at http://yourfanstasticsiteUrl.com/news/IDentry.setAlternateLinks(newArrayList(link));return entry;}}

步驟6.將類添加到Spring上下文

我正在使用xml方法。 因為我老了,我喜歡xml。 不,很認真,我使用xml是因為我可能想用不同的視圖(RSS 1.0,RSS 2.0等)聲明FeedController幾次。

這就是前面提到的spring-mvc.xml

<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns='http://www.springframework.org/schema/beans'xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd'><bean class='org.springframework.web.servlet.view.ContentNegotiatingViewResolver'><property name='mediaTypes'><map><entry key='atom' value='application/atom+xml'/><entry key='html' value='text/html'/></map></property><property name='viewResolvers'><list><bean class='org.springframework.web.servlet.view.BeanNameViewResolver'/></list></property></bean><bean class='eu.margiel.pages.confitura.feed.FeedController'><constructor-arg index='0' ref='newsRepository'/><constructor-arg index='1' value='atomFeedView'/></bean><bean id='atomFeedView' class='eu.margiel.pages.confitura.feed.AtomFeedView'/>
</beans>

您完成了。

之前曾有人要求我將所有工作代碼放入某個公共存儲庫中,所以這又是另一回事了。 我已經描述了我已經發布的內容,您可以從bitbucket中獲取提交。

參考: Solid Craft博客上來自我們JCG合作伙伴 Jakub Nabrdalik的Atom Feeds與Spring MVC 。


翻譯自: https://www.javacodegeeks.com/2012/10/spring-mvc-for-atom-feeds.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/370826.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/370826.shtml
英文地址,請注明出處:http://en.pswp.cn/news/370826.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python數據類型所占字節數_python標準數據類型 Bytes

預備知識&#xff1a; bin()&#xff1a; """ Return the binary representation of an integer. >>> bin(2796202) 0b1010101010101010101010 """ pass ord(): """ Return the Unicode code point for a one-character…

java第六次作業

《Java技術》第六次作業 &#xff08;一&#xff09;學習總結 1.用思維導圖對本周的學習內容進行總結。 2.當程序中出現異常時&#xff0c;JVM會依據方法調用順序依次查找有關的錯誤處理程序。可使用printStackTrace 和getMessage方法了解異常發生的情況。閱讀下面的程序&#…

華為鴻蒙不再孤,華為鴻蒙OS系統不再孤單!又一款國產系統啟動內測:再掀國產替代化...

【5月10日訊】相信大家都知道&#xff0c;備受廣大花粉們期待的鴻蒙OS系統終于開始推送公測版本了&#xff0c;并且適配機型也開始不斷地增多&#xff0c;而根據華為官方最新消息&#xff0c;華為鴻蒙OS系統將會在6月份開始大規模推送正式版鴻蒙系統&#xff0c;這無疑將會成為…

Spring系列合并

Spring Collection合并是我第一次遇到的功能&#xff0c;它是對StackOverflow 問題的回答 這是一種創建基本集合&#xff08;列表&#xff0c;集合&#xff0c;地圖或屬性&#xff09;并在其他Bean中修改此基本集合的方法&#xff0c;下面通過一個示例對此進行最好的解釋- 考慮…

CSS 水平垂直居中

方法一&#xff1a; 容器確定寬高&#xff1a;知識點&#xff1a;transform只能設置在display為block的元素上。 <head> <meta charset"UTF-8"> <title>Title</title> <style type"text/css"> #container{…

linux怎么進入文件夾_Linux基礎命令《上》

上一節介紹了VMware中安裝centos7以及克隆系統&#xff0c;之中用到的幾個命名還都是開發不常用的&#xff0c;這節課就準備講解一下入門的Linux命名&#xff0c;都是日常使用的。首先呢&#xff0c;我們進入系統后&#xff0c;得先知道我是誰&#xff0c;我在哪兒&#xff1f;…

UML學習(一)-----用例圖

1、什么是用例圖 用例圖源于Jacobson的OOSE方法&#xff0c;用例圖是需求分析的產物&#xff0c;描述了系統的參與者與系統進行交互的功能&#xff0c;是參與者所能觀察和使用到的系統功能的模型圖。它的主要目的就是幫助開發團隊以一種可視化的方式理解系統的功能需求&#xf…

首款鴻蒙系統終端n,榮耀智慧屏正式發布,首款搭載鴻蒙系統終端,家庭C位新選擇...

原標題&#xff1a;榮耀智慧屏正式發布&#xff0c;首款搭載鴻蒙系統終端&#xff0c;家庭C位新選擇智能手機的普及率越來越高&#xff0c;其所能夠承擔的功能也越來越多&#xff0c;電視機對于很多中青年的用戶來講&#xff0c;更多的時候就是個擺設。在家庭中&#xff0c;看電…

oracle如何保證數據一致性和避免臟讀

oracle通過undo保證一致性讀和不發生臟讀 1.不發生臟讀2.一致性讀3. 事務槽&#xff08;ITL&#xff09;小解1.不發生臟讀 例如&#xff1a;用戶A對表更新了&#xff0c;沒有提交&#xff0c;用戶B對進行查詢&#xff0c;沒有提交的更新不能出現在用戶的查詢結果中 舉例并通個d…

Google Guava BloomFilter

當Guava項目發布版本11.0時&#xff0c;新添加的功能之一是BloomFilter類。 BloomFilter是唯一的數據結構&#xff0c;用于指示元素是否包含在集合中。 使BloomFilter有趣的是&#xff0c;它將指示元素是否絕對不包含或可能包含在集合中。 永遠不會出現假陰性的特性使BloomFil…

php 編程祝新年快樂_用于測試自動化的7種編程語言

導讀&#xff1a;本文重點介紹測試自動化中排名前七位的編程語言。當人們想要開始做自動化測試&#xff0c;此時卻需要開發自動化測試腳本&#xff0c;也就是要學習一門編程語言。那么&#xff0c;我們怎樣邁出這一步&#xff1f;也有你已經精通一種編程語言&#xff0c;也可以…

Day1 了解web前端

Day1 了解web前端 一.職業發展路線: 前端頁面制作、前端開發、前端架構師 二.1)前端工程師主要職責: 利用HTML/CSS/JavaScript等各種Web技術進行客戶端產品的開發。完成客戶端程序&#xff08;也就是瀏覽器端&#xff09;的開發&#xff0c;同時結合后臺技術模擬整體效果&am…

已阻止應用程序訪問圖形硬件_玩轉智能硬件之Jetson Nano(三)深度學習環境搭建...

0、前言iotboy&#xff1a;玩轉智能硬件&#xff08;一&#xff09;Jetson Nano安裝篇?zhuanlan.zhihu.comiotboy&#xff1a;玩轉智能硬件&#xff08;二&#xff09;Jetson Nano配置篇?zhuanlan.zhihu.com在玩轉智能硬件&#xff08;一&#xff09;和&#xff08;二&#x…

Vue.js開發環境搭建的介紹

包含了最基礎的Vue.js的框架&#xff0c;包含了打包工具和測試工具&#xff0c;開發調試的最基本的服務器&#xff0c;不需要關注細節&#xff0c;只需關注Vuejs對項目的實現 npm在國內的網絡使用較慢&#xff0c;所以推薦下載安裝淘寶的鏡像 1&#xff1a; 2&#xff1a;安裝c…

html文件轉換html格式,pdf文件怎么轉換成html格式

PDF文件怎么轉換成html格式呢&#xff1f;html格式其實就是網頁格式&#xff0c;PDF文件和網頁文件一般情況下是兩種完全不搭邊的格式&#xff0c;但是不可否定的是辦公室的多樣化總有人會有這樣的需求&#xff0c;只要有需求就會有其相應的解決方案。我們可以利用PDF轉Word一樣…

Eclipse中的Github Gists

我想描述有關在Eclipse中集成GitHub Gists的簡單步驟。 有幾個來源促使我這樣做&#xff1a; Eclipse的GitHub Mylyn連接器 EGit / GitHub /用戶指南 http://eclipse.github.com 我一直在使用Eclipse Java EE發行版&#xff0c;其中已經安裝了Mylyn插件&#xff1a; 1.通…

CSS3景深-perspective

3D視圖正方體&#xff1a; 1 <!DOCTYPE html>2 <html lang"en">3 <head>4 <meta charset"UTF-8">5 <title>CSS3景深-perspective</title>6 </head>7 <style>8 #div1{9 position: rel…

python pool_派松水潭(Python Pool)

派松水潭(Python Pool)旅游景點類型&#xff1a;名勝Roebourne Winternoom Road , Roebourne , Western Australia , 6718Email:roetourbigpond.net.auWebsite:www.pilbaracoast.com派松水潭(Python Pool)坐落于羅伯恩(Roebourne)以南風景如畫的米爾斯特姆-奇切斯特國家公園內。…

【BZOJ4262】Sum 單調棧+線段樹

【BZOJ4262】Sum Description Input 第一行一個數 t&#xff0c;表示詢問組數。第一行一個數 t&#xff0c;表示詢問組數。接下來 t 行&#xff0c;每行四個數 l_1, r_1, l_2, r_2。Output 一共 t 行&#xff0c;每行一個數 Sum。Sample Input 4 1 3 5 7 2 4 6 8 1 1 9 9 9 9 1…

父類一實現serializable_我的java基礎學習易錯點和易忘點總結(一)

一.繼承A:子類只能繼承父類所有非私有的成員(成員方法和成員變量)B:子類不能繼承父類的構造方法&#xff0c;但是可以通過super關鍵字去訪問父類構造方法。二.繼承中構造方法的關系A:子類中所有的構造方法默認都會訪問父類中空參數的構造方法B:為什么呢?因為子類會繼承父類中的…