`
ssxxjjii
  • 浏览: 948606 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring 3 MVC ContentNegotiatingViewResolver Example

 
阅读更多

http://www.mkyong.com/spring-mvc/spring-3-mvc-contentnegotiatingviewresolver-example/

 

Spring 3, ContentNegotiatingViewResolver, is an interesting view resolver, which allow you to output a same resource (content or data) to different type of views like JSPXMLRSSJSON and etc. Put it simple, see following web requested URL, which will return in different views.

  1. http://www.mkyong.com/fruit/banana.rss , returned as RSS file.
  2. http://www.mkyong.com/fruit/banana.xml , returned as XML file.
  3. http://www.mkyong.com/fruit/banana.json , returned as JSON file.
  4. http://www.mkyong.com/fruit/banana, returned to your default view resolver.
Note
This ContentNegotiatingViewResolver first determine “which view resolver should return by file extension”, if no view is match, then use the default view resolver. Read this Spring documentation to study how it works.

In this tutorial, we show you how to use ContentNegotiatingViewResolver. At the end of this tutorial, a same model will be returned in different views – XML, JSON, RSS and JSP, based on it’s requested file extension.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. Jackson 1.7.1
  3. Rome 1.0.0
  4. JDK 1.6
  5. Maven 3
  6. Eclipse 3.6
Note
JAXB is bundled in JDK1.6, so, you don’t need to include it manually.

1. Project Dependency

Declares following dependencies in your Maven pom.xml file.

	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>
 
	<dependencies>
 
		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.7.1</version>
		</dependency>
 
		<!-- RSS -->
		<dependency>
			<groupId>net.java.dev.rome</groupId>
			<artifactId>rome</artifactId>
			<version>1.0.0</version>
		</dependency>
 
	</dependencies>
 
</project>
<iframe id="aswift_1" style="left: 0px; position: absolute; top: 0px;" name="aswift_1" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="728" height="90"></iframe>

2. Model

A Pojo, annotated with JAXB annotation, so that it can output in XML file. Besides, later we use this model to display in different views.

package com.mkyong.common.model;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name = "fruit")
public class Fruit {
 
	String name;
	int quality;
 
	public String getName() {
		return name;
	}
 
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}
 
	public int getQuality() {
		return quality;
	}
 
	@XmlElement
	public void setQuality(int quality) {
		this.quality = quality;
	}
 
	public Fruit(String name, int quality) {
		this.name = name;
		this.quality = quality;
	}
 
	public Fruit() {
	}
 
}

3. JSON and XML View

To output JSON and XML views, you don’t need to do any extra works, Spring MVC will handle the conversion automatically. Read this Spring MVC and XML, and Spring MVC and JSON examples.

4. RSS View

To output RSS View, you need to extend AbstractRssFeedView. Read this Spring 3 MVC and RSS example to know how it works.

package com.mkyong.common.rss;
 
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.mkyong.common.model.Fruit;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Content;
import com.sun.syndication.feed.rss.Item;
 
public class RssFeedView extends AbstractRssFeedView {
 
	@Override
	protected void buildFeedMetadata(Map<String, Object> model, Channel feed,
		HttpServletRequest request) {
 
		feed.setTitle("Sample Title");
		feed.setDescription("Sample Description");
		feed.setLink("http://google.com");
 
		super.buildFeedMetadata(model, feed, request);
	}
 
 
	@Override
	protected List<Item> buildFeedItems(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
 
		Fruit fruit = (Fruit) model.get("model");
		String msg = fruit.getName() + fruit.getQuality();
 
		List<Item> items = new ArrayList<Item>(1);
		Item item = new Item();
		item.setAuthor("mkyong");
		item.setLink("http://www.mkyong.com");
 
		Content content = new Content();
		content.setValue(msg);
 
		item.setContent(content);
 
		items.add(item);
 
		return items;
	}
}

5. JSP View

A JSP page to display the model data.

File : list.jsp

<html>
<body>
	<h1>Spring @MVC ContentNegotiatingViewResolver</h1>
 
	Fruit Name : ${model.name} <br />
	Fruit Quality : ${model.quality}
 
</body>
</html>

6. Controller

Spring controller, to generate a “fruit” model and return it.

package com.mkyong.common.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.mkyong.common.model.Fruit;
 
@Controller
@RequestMapping("/fruit")
public class FruitController {
 
	@RequestMapping(value="{fruitName}", method = RequestMethod.GET)
	public String getFruit(@PathVariable String fruitName, ModelMap model) {
 
		Fruit fruit = new Fruit(fruitName, 1000);
		model.addAttribute("model", fruit);
 
		return "list";
 
	}
 
}

7. ContentNegotiatingViewResolver example

The code should be self-explanatory. However, you have to define the “order” property, where lower value get higher priority. In this case, when a URL is requested, Spring MVC will use “ContentNegotiatingViewResolver” (order=1) to return a suitable view (based on file extension declared in “mediaTypes” property), if not match, then use “InternalResourceViewResolver” (order=2) to return a default JSP page.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
	<context:component-scan base-package="com.mkyong.common.controller" />
 
	<mvc:annotation-driven />
 
	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
	  <property name="order" value="1" />
	  <property name="mediaTypes">
		<map>
		   <entry key="json" value="application/json" />
		   <entry key="xml" value="application/xml" />
		   <entry key="rss" value="application/rss+xml" />
		</map>
	  </property>
 
	  <property name="defaultViews">
		<list>
		  <!-- JSON View -->
		  <bean
			class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
		  </bean>
 
		  <!-- RSS View -->
		  <bean class="com.mkyong.common.rss.RssFeedView" />
 
		  <!-- JAXB XML View -->
		  <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
			<constructor-arg>
				<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
				   <property name="classesToBeBound">
					<list>
					   <value>com.mkyong.common.model.Fruit</value>
					</list>
				   </property>
				</bean>
			</constructor-arg>
		  </bean>
		 </list>
	  </property>
	  <property name="ignoreAcceptHeader" value="true" />
 
	</bean>
 
	<!-- If no extension matched, use JSP view -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="order" value="2" />
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
 
</beans>

8. Demo

Same model and display in different views, via ContentNegotiatingViewResolver.

http://localhost:8080/SpringMVC/fruit/banana.xml , display as XML file.

spring mvc and xml demo

http://localhost:8080/SpringMVC/fruit/banana.json , display as JSON file.

spring mvc and json demo

http://localhost:8080/SpringMVC/fruit/banana.rss , display as RSS file.

spring mvc and RSS demo

http://localhost:8080/SpringMVC/fruit/banana , display as JSP page.

spring mvc and JSP demo
分享到:
评论

相关推荐

    Spring3 MVC 深入研究

    《Spring3 MVC 深入研究》 Spring3 MVC是Spring框架的重要组成部分,它是一个用于构建Web应用程序的轻量级、模型-视图-控制器(MVC)框架。本篇文章将深入探讨Spring3 MVC的核心概念、工作原理以及如何在实际项目中...

    spring3 MVC实战

    spring3 MVC实战

    spring3MVC 框架demo

    Spring3MVC是Spring框架的一个重要模块,专为构建Web应用程序提供模型-视图-控制器(MVC)架构支持。这个框架使得开发者可以更轻松地处理HTTP请求、数据绑定、验证以及视图渲染等任务。在"spring3MVC框架demo"中,...

    最全最经典spring-mvc教程

    Spring MVC 是一款强大的Java Web开发框架,用于构建高效、可维护和模块化的Web应用程序。它作为Spring框架的一部分,提供了一种优雅的方式来处理HTTP请求和响应,使得开发者可以专注于业务逻辑而不是底层实现。在这...

    spring3 mvc jar

    标题 "spring3 mvc jar" 指涉的是Spring框架的第三个主要版本的MVC模块。Spring MVC是Spring框架的一部分,专门用于构建Web应用程序。它提供了模型-视图-控制器(MVC)架构,帮助开发者将业务逻辑、数据处理和用户...

    spring-mvc-example:Spring MVC创作与使用

    spring-mvc-example 使用Spring-MVC创建数据库并创建数据库。 使用过的技术:Spring Tool Suite 4.1.2.RELEASE,apache-tomcat-9.0.43。 在Tomcat的Eclipse服务器和Eclipse中创建脚本,在区域设置中使用apache-...

    spring3mvc导入包

    Spring3MVC是Spring框架的一个重要模块,用于构建基于Java的Web应用程序。它提供了一个模型-视图-控制器(MVC)架构,帮助开发者将业务逻辑、数据处理和用户界面分离,实现更清晰的代码组织和更高的可维护性。在这个...

    Spring Web MVC外文翻译

    ### Spring Web MVC 外文翻译知识点解析 #### 一、Spring Web MVC介绍 Spring Web MVC 是基于 Servlet API 构建的原始 Web 框架,它从 Spring 框架诞生之初就被包含其中。正式名称“Spring Web MVC”来源于其源...

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    Spring MVC 是一个基于Java的轻量级Web应用框架,它是Spring框架的重要组成部分,主要用于构建Web应用程序的后端控制器。这个教程“Spring MVC - A Tutorial”旨在帮助开发者深入理解和掌握Spring MVC的核心概念和...

    精通Spring MVC 4

    Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。Spring MVC4是当前zuixin的版本,在众多特性上有了进一步的提升。, 在精通Spring...

    Spring Web MVC入门教程

    Spring Web MVC是一种基于MVC模式的轻量级Java Web应用框架,它是Spring框架的一部分,主要用于简化Web层的开发。Spring Web MVC允许开发者将应用程序分为三个主要组件:模型(Model)、视图(View)和控制器(Controller...

    spring-webmvc-5.0.9 jar包、源码和javadoc

    《Spring Web MVC 5.0.9:深度解析与应用》 Spring Web MVC是Spring框架的核心模块之一,专为构建Web应用程序提供模型-视图-控制器(MVC)架构支持。在Spring 5.0.9这个版本中,它延续了Spring对开发者友好、灵活且...

    Spring3MVC和jQuery的集成

    Spring3 MVC和jQuery是两种非常重要的Web开发技术。Spring3 MVC是Spring框架的一部分,用于构建后端MVC架构的应用程序,而jQuery则是一种强大的JavaScript库,简化了前端的DOM操作、事件处理和Ajax交互。本篇文章将...

    Spring3MVC注解(附实例).doc

    Spring3MVC 注解详解 Spring3MVC 注解是基于 Java 的 Spring 框架中的一种编程模型,旨在简化 Web 应用程序的开发。下面将详细介绍 Spring3MVC 注解的概念、实现机制、配置方法和实践示例。 Spring3MVC 注解的...

    Spring3MVC真正入门资料.doc

    Spring3MVC真正入门资料 本文将详细介绍 Spring3MVC 框架的入门知识,包括核心类与接口、核心流程图、DispatcherServlet 说明等。 核心类与接口 在 Spring3MVC 框架中,有几个重要的接口与类,了解它们的作用可以...

    spring3 mvc实例

    Spring3 MVC是一个强大的Java web开发框架,由Spring IO项目维护,它为构建基于模型-视图-控制器(MVC)架构的应用程序提供了全面的支持。在本实例中,我们将会探讨Spring3 MVC的核心特性、配置、控制器、视图解析...

    spring-mvc-官方中文文档

    3. **HandlerMapping**:该接口负责将请求与处理器(Controller)进行匹配,Spring MVC 提供了多种实现,如基于注解的 HandlerMapping,可以根据 @RequestMapping 注解将 URL 映射到控制器方法。 4. **...

    spring3.0 MVC中文教程

    3. **第3部分:在Spring 3.0 MVC中进行表单处理** - 探讨如何使用Spring MVC处理表单提交,包括数据绑定和验证。 4. **第4部分:Spring 3 MVC的Tiles支持与Eclipse中的插件教程** - Tiles框架是一种用于管理页面布局...

Global site tag (gtag.js) - Google Analytics