SpringMVC 中整合JSON、XML视图一

2014-11-24 00:45:01 · 作者: · 浏览: 0

SpringMVC中整合了JSON、XML的视图,可以通过这些视图完成Java对象到XML、JSON的转换。转换XML提供了MarshallingView,开发者只需用注入相应的marshaller、和属性配置,即可自动完成Java的Model对象中的数据到XML的编组。

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

一、 准备工作

1、 本次程序会涉及到Jackson、xStream、Jibx、Jaxb2、castor等技术

这篇文章中涉及到的内容应该对你有不少帮助。

2、 jar包下载

spring各版本jar下载地址:http://ebr.springsource.com/repository/app/library/detail name=org.springframework.spring

相关的依赖包也可以在这里找到:http://ebr.springsource.com/repository/app/library

3、 至少需要以下jar包

clip_image002

4、 当前工程的web.xml配置

< xml version="1.0" encoding="UTF-8" >
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<-- 配置Spring核心控制器 -->

dispatcher
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
/WEB-INF/dispatcher.xml

1



dispatcher
*.do


<-- 解决工程编码过滤器 -->

characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter

encoding
UTF-8




characterEncodingFilter
/*



index.jsp

5、 WEB-INF中的dispatcher.xml配置

< xml version="1.0" encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<-- 注解探测器 -->


<-- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 -->







启动后,可以看到index.jsp 没有出现异常或错误。那么当前SpringMVC的配置就成功了。


二、 利用Jaxb2编组XML

1、 Jaxb2可以完成XML和Java的相互转换,在WebService中用得较多。前面也介绍过Jaxb2 的用法。

在线博文:

For cnblogs:http://www.cnblogs.com/hoojo/archive/2011/04/26/2029011.html

For csdn:aspx">http://blog.csdn.net/IBM_hoojo/archive/2011/04/26/6363491.aspx

2、 首先在dispatcher.xml中配置Jaxb2的marshaller的视图,配置如下:

<-- xml视图,Jaxb2Marshaller,需要配置对象和对象添加Annotation xml注解,不需要添加额外的jar包 -->