atom feed_适用于Atom Feed的Spring MVC

atom feed

如何仅使用两个类就将提要(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

atom feed

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/352037.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

argb可以和rgb同步吗_神光同步酷炫幻彩,安钛克光棱120 RGB风扇套装

目前这个时代&#xff0c;电脑的各种配件来说&#xff0c;走向了万物皆要有光的风格。相信发光耳机&#xff0c;发光键盘&#xff0c;发光鼠标大家也都见过不少。侧透机箱甚至全透机箱搭配各类酷炫光效在电竞游戏领域也变得越来越火。许多小伙伴在组装一款电脑时也会选择发光风…

使用GDB命令行调试器调试C/C++程序

编译自&#xff1a;http://xmodulo.com/gdb-command-line-debugger.html 作者&#xff1a; Adrien Brochard 原创&#xff1a;LCTT https://linux.cn/article-4302-1.html 译者&#xff1a; SPccman 本文地址&#xff1a;https://linux.cn/article-4302-1.html 没有调试器的…

制造业物料清单BOM、智能文档阅读、科学文献影响因子、Celebrated Italian mathematician ZepartzatT Gozinto 与 高津托图...

意大利数学家Z.高津托 意大利伟大数学家Sire Zepartzatt Gozinto的生卒年代是一个谜[1]&#xff0c;但是他发明的 “高筋图” 在 制造资源管理、物料清单&#xff08;BOM&#xff09;管理、智能阅读、科学文献影响因子计算 等方面具有重要应用。 高津托图 下图是一个制造业物料…

Dools的DMN运行时示例

正如去年宣布的那样 &#xff0c;Drools 7.0将在合规性级别3上为DMN模型提供完整的运行时支持。 在撰写本文时&#xff0c;运行时实现功能已经完成 &#xff0c;并且团队现在正在努力进行改进&#xff0c;以进行错误修复和用户友好。 不幸的是&#xff0c;对于7.0版本&#x…

走向开放、拥抱开源 —— 如何为代码选择一个合适的开源协议

目录 一. 前言 二. 开源协议选择 2.1. 何为 LICENCE&#xff1f; 2.2. 快速选择开源协议 三. 主流开源许可协议&#xff08;Open Source License&#xff09; 3.1. 常用开源协议 3.2. MIT 协议 3.3. BSD 协议 3.4. Apache Licence 协议 3.5. LGPL 协议 3.6. GPL 四…

MATLAB提取矩阵中的一部分

MATLAB对矩阵的操作十分灵活&#xff0c;下面对最近遇到的进行总结&#xff1a; 格式A(m,n)&#xff0c;用于提取矩阵A中符合m,n要求的部分 1、提取某个元素&#xff0c;则m,n为数字标量&#xff0c;如A&#xff08;2,3&#xff09;为第二行第三列的元素。 2、提取某行某列 A…

garch模型python步骤_GARCH模型的建模步骤?

泻药&#xff0c;我将建立道琼斯工业平均指数(DJIA)日交易量对数比的ARMA-GARCH模型来演示建模步骤。原文链接&#xff1a;R语言&#xff1a; GARCH模型股票交易量的研究道琼斯股票市场指数​tecdat.cn获取数据load(fileDowEnvironment.RData)日交易量每日交易量内发生的 变化。…

JavaScript里面的居民们1-数据

编码 首先练习数字相关的一些操作&#xff1a; <div><label>Number A:<input id"radio-a" type"radio" name"math-obj" value"a"></label><input id"num-a" type"text"> <label…

GCC + pthread

多线程介绍POSIX 1003.1-2001 定义了多线程编程的标准API。这个API就是广为人知的pthreads。它的目的在于为跨平台编写多线程程序提供便利。本文介绍了Linux 和 WIN32 平台下的多线程程序的编写方法Linux 系统对 pthreads 提供了良好的支持。一般地安装完Linux系统后在/usr/inc…

MATLAB的size、length函数

size&#xff08;&#xff09;&#xff1a;获取矩阵的行数和列数 &#xff08;1&#xff09;ssize(A), 返回一个行向量&#xff0c;该行向量的第一个元素是矩阵的行数&#xff0c;第二个元素是矩阵的列数。 &#xff08;2&#xff09;[r,c]size(A), 当有两个输出参数…

python两个时间内的工作日_如何在Python中找到两个日期之间的星期一或任何其他工作日的数目?...

这是高效的-即使在开始和结束之间有一万天的时间-而且仍然非常灵活(它在sum函数内最多迭代7次)&#xff1a;def intervening_weekdays(start, end, inclusiveTrue, weekdays[0, 1, 2, 3, 4]):if isinstance(start, datetime.datetime):start start.date() # make a date from …

JS--继承

构造函数、原型、实例、原型链之间的联系 描述&#xff1a;每个构造函数都有一个原型对象&#xff1b; 每个原型对象都有一个指针&#xff0c;指向构造函数&#xff1b; 每个实例对象都有一个内部指针&#xff0c;指向原型对象&#xff1b; 若此时的原型对象是另一个类型的实例…

Linux C/C++多线程pthread实例

inux中C/C开发多线程程序多遵循POSIX线程接口&#xff08;也就是pthread&#xff09;&#xff0c;pthread涉及函数很多个&#xff08;更多参见pthread.h头文件&#xff09;&#xff0c;常用的有pthread_create、pthread_dispath、pthread_mutex_lock&#xff08;互斥锁定&#…

python 横向合并_使用Python横向合并excel文件的实例

起因&#xff1a;有一批数据需要每个月进行分析&#xff0c;数据存储在excel中&#xff0c;行标题一致&#xff0c;需要横向合并进行分析。数据示意&#xff1a;具有多个代码&#xff1a;# -*- coding: utf-8 -*-"""Created on Sun Nov 12 11:19:03 2017author:…

javafx游戏_JavaFX游戏(四连环)

javafx游戏这是我的第一个JavaFX游戏教程&#xff0c;也是我关于JavaFX面板的第一篇博客文章。 我仅用200几行代码就完成了这四款连接游戏&#xff0c;足以应付一个简单的游戏。 我在这里使用GridPane面板对磁盘进行布局&#xff0c;GridPane是JavaFX布局窗格之一&#xff0c;但…

Matlab的sort函数

1、Matlab自带排序函数sort用法 [Y,I] sort(X,DIM,MODE) sort函数默认Mode为ascend为升序&#xff0c;sort(X,descend)为降序排列。 sort(X)若X是矩阵&#xff0c;默认对X的各列进行升序排列 sort(X,dim) dim1时等效sort(X)dim2时表示对X中的各行元素升序…

django HttpResponse的用法

一、传json字典 def back_json(rquest):#JsonResponse父类是HttpResponse&#xff0c;原码里调用了json.dumps()from django.http import JsonResponseback_msg {name:name,age:123}return JsonResponse(back_msg) 二、传列表 def back_json(rquest):#JsonResponse父类是HttpR…

gcc/g++ 链接库的编译与链接

程序编译一般需要经预处理、编译、汇编和链接几个步骤。在实际应用中&#xff0c;有些公共代码需要反复使用&#xff0c;就把这些代码编译成为“库”文件。在链接步骤中&#xff0c;连接器将从库文件取得所需的代码&#xff0c;复制到生成的可执行文件中&#xff0c;这种库称为…

Speedment 3.0的新功能

如果您关注我的博客&#xff0c;那么您会知道我已经参与开源项目Speedment已有一段时间了。 在夏季和秋季&#xff0c;我完成了工具包的下一个3.0.0大型发行版的大量工作。 在这篇文章中&#xff0c;我将展示我们已经在平台中内置的一些很酷的新功能&#xff0c;并说明如何入门…

Matlab在坐标点上按顺序标序号

程序一&#xff1a; clear x[1 3 7 10]; y[2 4 9 43]; plot(x,y,r-) hold on for i1:4%用这个循环cnum2str(i);c[ ,c];text(x(i),y(i),c) end axis([0 10 0 50]) 程序二&#xff1a; xrand(10,1)*10; yrand(10,1)*10; %x,y表示任意10个点的坐标 plot(x,y,*); for i1:10text(x(…