Учебники

Spring MVC – Пример создания RSS-канала

В следующем примере показано, как создать RSS-канал с помощью Spring Web MVC Framework. Для начала давайте наладим работающую среду Eclipse IDE, а затем рассмотрим следующие шаги для разработки веб-приложения на основе динамических форм с использованием Spring Web Framework.

шаг Описание
1 Создайте проект с именем TestWeb в пакете com.tutorialspoint, как описано в главе Spring MVC – Hello World.
2 Создайте Java-классы RSSMessage, RSSFeedViewer и RSSController в пакете com.tutorialspoint.
3 Загрузите римскую библиотеку Rome и ее зависимости rome-utils, jdom и slf4j с той же страницы репозитория maven. Поместите их в свой CLASSPATH.
4 Создайте файл свойств messages.properties в папке SRC.
5 Последний шаг – создание содержимого исходного файла и файлов конфигурации и экспорт приложения, как описано ниже.

RSSMessage.java

package com.tutorialspoint;

import java.util.Date;

public class RSSMessage {
   String title;
   String url;
   String summary;
   Date createdDate;
   public String getTitle() {
      return title;
   }
   public void setTitle(String title) {
      this.title = title;
   }
   public String getUrl() {
      return url;
   }
   public void setUrl(String url) {
      this.url = url;
   }
   public String getSummary() {
      return summary;
   }
   public void setSummary(String summary) {
      this.summary = summary;
   }
   public Date getCreatedDate() {
      return createdDate;
   }
   public void setCreatedDate(Date createdDate) {
      this.createdDate = createdDate;
   }	
}

RSSFeedViewer.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.feed.AbstractRssFeedView;

import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;

public class RSSFeedViewer extends AbstractRssFeedView {

   @Override
   protected void buildFeedMetadata(Map<String, Object> model, Channel feed,
      HttpServletRequest request) {

      feed.setTitle("TutorialsPoint Dot Com");
      feed.setDescription("Java Tutorials and Examples");
      feed.setLink("http://www.tutorialspoint.com");

      super.buildFeedMetadata(model, feed, request);
   }

   @Override
   protected List<Item> buildFeedItems(Map<String, Object> model,
      HttpServletRequest request, HttpServletResponse response) throws Exception {
   
      List<RSSMessage> listContent = (List<RSSMessage>) model.get("feedContent");
      List<Item> items = new ArrayList<Item>(listContent.size());

      for(RSSMessage tempContent : listContent ){

         Item item = new Item();

         Content content = new Content();
         content.setValue(tempContent.getSummary());
         item.setContent(content);

         item.setTitle(tempContent.getTitle());
         item.setLink(tempContent.getUrl());
         item.setPubDate(tempContent.getCreatedDate());

         items.add(item);
      }

      return items;		
   }
}

RSSController.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class RSSController {
   @RequestMapping(value="/rssfeed", method = RequestMethod.GET)
   public ModelAndView getFeedInRss() {

      List<RSSMessage> items = new ArrayList<RSSMessage>();

      RSSMessage content  = new RSSMessage();
      content.setTitle("Spring Tutorial");
      content.setUrl("http://www.tutorialspoint/spring");
      content.setSummary("Spring tutorial summary...");
      content.setCreatedDate(new Date());
      items.add(content);

      RSSMessage content2  = new RSSMessage();
      content2.setTitle("Spring MVC");
      content2.setUrl("http://www.tutorialspoint/springmvc");
      content2.setSummary("Spring MVC tutorial summary...");
      content2.setCreatedDate(new Date());
      items.add(content2);

      ModelAndView mav = new ModelAndView();
      mav.setViewName("rssViewer");
      mav.addObject("feedContent", items);

      return mav;
   }
}

TestWeb-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"   
   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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:component-scan base-package = "com.tutorialspoint" />

   <bean class = "org.springframework.web.servlet.view.BeanNameViewResolver" />

   <bean id = "rssViewer" class = "com.tutorialspoint.RSSFeedViewer" />
</beans>

Здесь мы создали канал RSS POJO RSSMessage и средство просмотра сообщений RSS, которое расширяет AbstractRssFeedView и переопределяет его метод. В RSSController мы создали образец RSS-канала.

Когда вы закончите создавать исходные файлы и файлы конфигурации, экспортируйте ваше приложение. Щелкните правой кнопкой мыши свое приложение, выберите « Экспорт» → «Файл WAR» и сохраните файл TestWeb.war в папке веб-приложений Tomcat.

Теперь запустите сервер Tomcat и убедитесь, что вы можете получить доступ к другим веб-страницам из папки веб-приложений с помощью стандартного браузера. Попробуйте URL – http: // localhost: 8080 / TestWeb / rssfeed, и мы увидим следующий экран.