`
yuanlanjun
  • 浏览: 1184587 次
文章分类
社区版块
存档分类
最新评论

SpringMVC 中整合JSON、XML视图一

 
阅读更多

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等技术,如果你对这些技术还不是很了解。建议阅读:http://www.cnblogs.com/hoojo/archive/2011/04/27/2030264.html

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

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"?>
<!--CRLF-->
web-app version="2.4" 
<!--CRLF-->
    xmlns="http://java.sun.com/xml/ns/j2ee" 
<!--CRLF-->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
<!--CRLF-->
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
<!--CRLF-->
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--CRLF-->
    
<!--CRLF-->
    -- 配置Spring核心控制器 -->
<!--CRLF-->
    servlet>
<!--CRLF-->
        servlet-name>dispatcher/servlet-name>
<!--CRLF-->
        servlet-class>org.springframework.web.servlet.DispatcherServlet/servlet-class>
<!--CRLF-->
        init-param>
<!--CRLF-->
            param-name>contextConfigLocation/param-name>
<!--CRLF-->
            param-value>/WEB-INF/dispatcher.xml/param-value>
<!--CRLF-->
        /init-param>
<!--CRLF-->
        load-on-startup>1/load-on-startup>
<!--CRLF-->
    /servlet>
<!--CRLF-->
    
<!--CRLF-->
    servlet-mapping>
<!--CRLF-->
        servlet-name>dispatcher/servlet-name>
<!--CRLF-->
        url-pattern>*.do/url-pattern>
<!--CRLF-->
    /servlet-mapping>
<!--CRLF-->
    
<!--CRLF-->
    -- 解决工程编码过滤器 -->
<!--CRLF-->
    filter>
<!--CRLF-->
        filter-name>characterEncodingFilter/filter-name>
<!--CRLF-->
        filter-class>org.springframework.web.filter.CharacterEncodingFilter/filter-class>
<!--CRLF-->
        init-param>
<!--CRLF-->
            param-name>encoding/param-name>
<!--CRLF-->
            param-value>UTF-8/param-value>
<!--CRLF-->
        /init-param>
<!--CRLF-->
    /filter>
<!--CRLF-->
    
<!--CRLF-->
    filter-mapping>
<!--CRLF-->
        filter-name>characterEncodingFilter/filter-name>
<!--CRLF-->
        url-pattern>/*/url-pattern>
<!--CRLF-->
    /filter-mapping>
<!--CRLF-->
    
<!--CRLF-->
    welcome-file-list>
<!--CRLF-->
      welcome-file>index.jsp/welcome-file>
<!--CRLF-->
    /welcome-file-list>
<!--CRLF-->
/web-app>
<!--CRLF-->

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

?xml version="1.0" encoding="UTF-8"?>
<!--CRLF-->
beans xmlns="http://www.springframework.org/schema/beans"
<!--CRLF-->
    xmlns:mvc="http://www.springframework.org/schema/mvc"
<!--CRLF-->
    xmlns:context="http://www.springframework.org/schema/context"
<!--CRLF-->
    xmlns:util="http://www.springframework.org/schema/util"
<!--CRLF-->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!--CRLF-->
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
<!--CRLF-->
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<!--CRLF-->
    http://www.springframework.org/schema/mvc
<!--CRLF-->
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
<!--CRLF-->
    http://www.springframework.org/schema/context 
<!--CRLF-->
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
<!--CRLF-->
    http://www.springframework.org/schema/util
<!--CRLF-->
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!--CRLF-->
    
<!--CRLF-->
    -- 注解探测器 -->
<!--CRLF-->
    context:component-scan base-package="com.hoo.controller"/>
<!--CRLF-->
    
<!--CRLF-->
    -- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 -->
<!--CRLF-->
    bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<!--CRLF-->
        property name="order" value="1"/>
<!--CRLF-->
    /bean>
<!--CRLF-->
    
<!--CRLF-->
    bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--CRLF-->
        property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--CRLF-->
    /bean>
<!--CRLF-->
/beans>
<!--CRLF-->

启动后,可以看到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:http://blog.csdn.net/IBM_hoojo/archive/2011/04/26/6363491.aspx

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

-- xml视图,Jaxb2Marshaller,需要配置对象和对象添加Annotation xml注解,不需要添加额外的jar包 -->
<!--CRLF-->
bean name="jaxb2MarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<!--CRLF-->
    constructor-arg>
<!--CRLF-->
        bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<!--CRLF-->
            property name="classesToBeBound">
<!--CRLF-->
                array>
<!--CRLF-->
                    value>com.hoo.entity.User/value>
<!--CRLF-->
                    value>com.hoo.entity.AccountBean/value>
<!--CRLF-->
                    value>com.hoo.entity.MapBean/value>
<!--CRLF-->
                    value>com.hoo.entity.ListBean/value>
<!--CRLF-->
                /array>
<!--CRLF-->
            /property>
<!--CRLF-->
        /bean>
<!--CRLF-->
    /constructor-arg>
<!--CRLF-->
/bean>
<!--CRLF-->

Jaxb2的jar在jdk中已经包含,所以不需要添加额外的jar包。详细信息你可以参考1中的博文。上面的jaxb2MarshallingView视图的class是MarshallingView,它有一个构造器需要传递一个Marshaller。Marshaller主要完成编组,即将Java对象转换成XML的这么一个东东。我们在这个构造器中注入了Jaxb2Marshaller这个类,这个bean有一个classesToBeBound属性,这个属性是一个数组。需要将即将转换成XML的Java对象配置在这里。而且这些对象需要进行Annotation注解。

3、 创建Jaxb2MarshallingViewController,完成Java对象到XML的转换

单个JavaBean的转换,代码如下:

package com.hoo.controller;
<!--CRLF-->

<!--CRLF-->

    
import java.util.ArrayList;
<!--CRLF-->
import java.util.Date;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import org.springframework.stereotype.Controller;
<!--CRLF-->
import org.springframework.web.bind.annotation.RequestMapping;
<!--CRLF-->
import org.springframework.web.servlet.ModelAndView;
<!--CRLF-->
import com.hoo.entity.AccountBean;
<!--CRLF-->
import com.hoo.entity.Brithday;
<!--CRLF-->
import com.hoo.entity.DifferBean;
<!--CRLF-->
import com.hoo.entity.ListBean;
<!--CRLF-->
import com.hoo.entity.MoreBean;
<!--CRLF-->
import com.hoo.entity.User;
<!--CRLF-->

<!--CRLF-->

    
/**
<!--CRLF-->
 * function:Jaxb2MarshallingView 视图,利用Jaxb2进行Java对象到XML的转换技术
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午03:20:23
<!--CRLF-->
 * @file Jaxb2MarshallingViewController.java
<!--CRLF-->
 * @package com.hoo.controller
<!--CRLF-->
 * @project SpringMVC4View
<!--CRLF-->
 * @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
 * @email hoojo_@126.com
<!--CRLF-->
 * @version 1.0
<!--CRLF-->
 */
<!--CRLF-->
@Controller
<!--CRLF-->
@RequestMapping("/jaxb2/view")
<!--CRLF-->
public class Jaxb2MarshallingViewController {
<!--CRLF-->
    
<!--CRLF-->
    /*
<!--CRLF-->
     * MarshallingView Jaxb2Marshaller 需要配置转换成xml的java对象的Annotation
<!--CRLF-->
     */
<!--CRLF-->
    @RequestMapping("/doXMLJaxb2")
<!--CRLF-->
    public ModelAndView doXMLJaxb2View() {
<!--CRLF-->
        System.out.println("#################ViewController doXMLJaxb2View##################");
<!--CRLF-->
        ModelAndView mav = new ModelAndView("jaxb2MarshallingView");
<!--CRLF-->
        
<!--CRLF-->
        AccountBean bean = new AccountBean();
<!--CRLF-->
        bean.setAddress("address");
<!--CRLF-->
        bean.setEmail("email");
<!--CRLF-->
        bean.setId(1);
<!--CRLF-->
        bean.setName("haha");
<!--CRLF-->
        Brithday day = new Brithday();
<!--CRLF-->
        day.setBrithday("2010-11-22");
<!--CRLF-->
        bean.setBrithday(day);
<!--CRLF-->
        
<!--CRLF-->
        mav.addObject(bean);
<!--CRLF-->
        
<!--CRLF-->
        return mav;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

上面的代码的ModelAndView配置了jaxb2MarshallingView这个视图,就表示结果集会通过这个视图进行编组后显示。上面需要转换的AccountBean和Birthday对象,这些对象需要配置annotation,前面已经讲到annotation对JavaBean转换XML的作用。我们来看看AccountBean对象代码:

package com.hoo.entity;
<!--CRLF-->

<!--CRLF-->

    
import javax.xml.bind.annotation.XmlElement;
<!--CRLF-->
import javax.xml.bind.annotation.XmlRootElement;
<!--CRLF-->

<!--CRLF-->

    
@XmlRootElement(name = "account")
<!--CRLF-->
public class AccountBean {
<!--CRLF-->
    private int id;
<!--CRLF-->
    private String name;
<!--CRLF-->
    private String email;
<!--CRLF-->
    private String address;
<!--CRLF-->
    private Brithday brithday;
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public Brithday getBrithday() {
<!--CRLF-->
        return brithday;
<!--CRLF-->
    }
<!--CRLF-->
    public void setBrithday(Brithday brithday) {
<!--CRLF-->
        this.brithday = brithday;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public int getId() {
<!--CRLF-->
        return id;
<!--CRLF-->
    }
<!--CRLF-->
    public void setId(int id) {
<!--CRLF-->
        this.id = id;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public String getName() {
<!--CRLF-->
        return name;
<!--CRLF-->
    }
<!--CRLF-->
    public void setName(String name) {
<!--CRLF-->
        this.name = name;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public String getEmail() {
<!--CRLF-->
        return email;
<!--CRLF-->
    }
<!--CRLF-->
    public void setEmail(String email) {
<!--CRLF-->
        this.email = email;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public String getAddress() {
<!--CRLF-->
        return address;
<!--CRLF-->
    }
<!--CRLF-->
    public void setAddress(String address) {
<!--CRLF-->
        this.address = address;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    @Override
<!--CRLF-->
    public String toString() {
<!--CRLF-->
        return this.name + "#" + this.id + "#" + this.address + "#" + this.brithday + "#" + this.email;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

在getter方法都有部分注解,如果你想了解更多的jaxb2的相关技术,参考:http://www.cnblogs.com/hoojo/archive/2011/04/26/2029011.html

Brithday

package com.hoo.entity;
<!--CRLF-->

<!--CRLF-->

    
public class Brithday {
<!--CRLF-->
    private String brithday;
<!--CRLF-->
    
<!--CRLF-->
    public Brithday() {}
<!--CRLF-->
    
<!--CRLF-->
    public Brithday(String brithday) {
<!--CRLF-->
        this.brithday = brithday;
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    public String getBrithday() {
<!--CRLF-->
        return brithday;
<!--CRLF-->
    }
<!--CRLF-->

<!--CRLF-->

    
    public void setBrithday(String brithday) {
<!--CRLF-->
        this.brithday = brithday;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

Brithday是AccountBean中的一个属性,在AccountBean中已经注解过。这里就不需要进行注解配置。

通过浏览器请求:http://localhost:8080/SpringMVC4View/jaxb2/view/doXMLJaxb2.do

结果如下:

?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--CRLF-->
account>address>address/address>brithday>brithday>2010-11-22/brithday>/brithday>
<!--CRLF-->
email>email/email>id>1/id>name>haha/name>/account>
<!--CRLF-->

4、 转换带List属性的JavaEntity

/**
<!--CRLF-->
 * function:转换带有List属性的JavaBean
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午05:32:22
<!--CRLF-->
 * @return
<!--CRLF-->
 */
<!--CRLF-->
@RequestMapping("/doListXMLJaxb2")
<!--CRLF-->
public ModelAndView doListXMLJaxb2View() {
<!--CRLF-->
    System.out.println("#################ViewController doListXMLJaxb2View##################");
<!--CRLF-->
    ModelAndView mav = new ModelAndView("jaxb2MarshallingView");
<!--CRLF-->
    ListObject> beans = new ArrayListObject>(); 
<!--CRLF-->
    for (int i = 0; i  3; i++) {
<!--CRLF-->
        AccountBean bean = new AccountBean();
<!--CRLF-->
        bean.setAddress("address#" + i);
<!--CRLF-->
        bean.setEmail("email" + i + "@12" + i + ".com");
<!--CRLF-->
        bean.setId(1 + i);
<!--CRLF-->
        bean.setName("haha#" + i);
<!--CRLF-->
        Brithday day = new Brithday();
<!--CRLF-->
        day.setBrithday("2010-11-2" + i);
<!--CRLF-->
        bean.setBrithday(day);
<!--CRLF-->
        beans.add(bean);
<!--CRLF-->
        
<!--CRLF-->
        User user = new User();
<!--CRLF-->
        user.setAddress("china GuangZhou# " + i);
<!--CRLF-->
        user.setAge(23 + i);
<!--CRLF-->
        user.setBrithday(new Date());
<!--CRLF-->
        user.setName("jack#" + i);
<!--CRLF-->
        user.setSex(Boolean.parseBoolean(i + ""));
<!--CRLF-->
        beans.add(user);
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    ListBean list = new ListBean();
<!--CRLF-->
    list.setList(beans);
<!--CRLF-->
    mav.addObject(list);
<!--CRLF-->
    
<!--CRLF-->
    return mav;
<!--CRLF-->
}
<!--CRLF-->
ListBean注解过的代码
package com.hoo.entity;
<!--CRLF-->

<!--CRLF-->

    
import java.util.List;
<!--CRLF-->
import javax.xml.bind.annotation.XmlElement;
<!--CRLF-->
import javax.xml.bind.annotation.XmlElements;
<!--CRLF-->
import javax.xml.bind.annotation.XmlRootElement;
<!--CRLF-->

<!--CRLF-->

    
@SuppressWarnings("unchecked")
<!--CRLF-->
@XmlRootElement
<!--CRLF-->
public class ListBean {
<!--CRLF-->
    private String name;
<!--CRLF-->
    private List list;
<!--CRLF-->
    
<!--CRLF-->
    @XmlElements({
<!--CRLF-->
        @XmlElement(name = "user", type = User.class),
<!--CRLF-->
        @XmlElement(name = "account", type = AccountBean.class),
<!--CRLF-->
    })
<!--CRLF-->
    public List getList() {
<!--CRLF-->
        return list;
<!--CRLF-->
    }
<!--CRLF-->

<!--CRLF-->

    
    public void setList(List list) {
<!--CRLF-->
        this.list = list;
<!--CRLF-->
    }
<!--CRLF-->

<!--CRLF-->

    
    public String getName() {
<!--CRLF-->
        return name;
<!--CRLF-->
    }
<!--CRLF-->

<!--CRLF-->

    
    public void setName(String name) {
<!--CRLF-->
        this.name = name;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

通过上面的注解可以看出List中只能存储User、AccountBean对象,关于User对象的代码和AccountBean对象的是一样的,只是类名不同而已。读者可以自己添加。在WebBrowser中请求:http://localhost:8080/SpringMVC4View/jaxb2/view/doListXMLJaxb2.do

结果如下:

?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--CRLF-->
listBean>
<!--CRLF-->
account>address>address#0/address>brithday>brithday>2010-11-20/brithday>/brithday>
<!--CRLF-->
email>email0@120.com/email>id>1/id>name>haha#0/name>/account>
<!--CRLF-->
user>address>china GuangZhou# 0/address>age>23/age>
<!--CRLF-->
brithday>2011-04-27T17:02:38.028+08:00/brithday>name>jack#0/name>sex>false/sex>/user>
<!--CRLF-->
account>address>address#1/address>brithday>brithday>2010-11-21/brithday>/brithday>
<!--CRLF-->
email>email1@121.com/email>id>2/id>name>haha#1/name>/account>
<!--CRLF-->
user>address>china GuangZhou# 1/address>age>24/age>
<!--CRLF-->
brithday>2011-04-27T17:02:38.028+08:00/brithday>name>jack#1/name>sex>false/sex>/user>
<!--CRLF-->
account>address>address#2/address>brithday>brithday>2010-11-22/brithday>/brithday>
<!--CRLF-->
email>email2@122.com/email>id>3/id>name>haha#2/name>/account>
<!--CRLF-->
user>address>china GuangZhou# 2/address>age>25/age>
<!--CRLF-->
brithday>2011-04-27T17:02:38.028+08:00/brithday>name>jack#2/name>sex>false/sex>/user>
<!--CRLF-->
/listBean>
<!--CRLF-->

5、 转换带有Map属性的JavaBean,Jaxb2转换Map有点复杂,先看看代码:

/**
<!--CRLF-->
 * function:转换带有Map属性的JavaBean
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午05:32:42
<!--CRLF-->
 * @return
<!--CRLF-->
 */
<!--CRLF-->
@RequestMapping("/doMapXMLJaxb2")
<!--CRLF-->
public ModelAndView doMapXMLJaxb2View() {
<!--CRLF-->
    System.out.println("#################ViewController doMapXMLJaxb2View##################");
<!--CRLF-->
    ModelAndView mav = new ModelAndView("jaxb2MarshallingView");
<!--CRLF-->
    
<!--CRLF-->
    MapBean mapBean = new MapBean();
<!--CRLF-->
    
<!--CRLF-->
    HashMap<string accountbean> map = <span style="color: #0000ff">new</span> HashMap<string accountbean>();</string></string>
<!--CRLF-->
    AccountBean bean = new AccountBean();
<!--CRLF-->
    bean.setAddress("北京");
<!--CRLF-->
    bean.setEmail("email");
<!--CRLF-->
    bean.setId(1);
<!--CRLF-->
    bean.setName("jack");
<!--CRLF-->
    Brithday day = new Brithday();
<!--CRLF-->
    day.setBrithday("2010-11-22");
<!--CRLF-->
    bean.setBrithday(day);
<!--CRLF-->
    map.put("NO1", bean);
<!--CRLF-->
    
<!--CRLF-->
    bean = new AccountBean();
<!--CRLF-->
    bean.setAddress("china");
<!--CRLF-->
    bean.setEmail("tom@125.com");
<!--CRLF-->
    bean.setId(2);
<!--CRLF-->
    bean.setName("tom");
<!--CRLF-->
    day = new Brithday("2011-11-22");
<!--CRLF-->
    bean.setBrithday(day);
<!--CRLF-->
    map.put("NO2", bean);
<!--CRLF-->
    
<!--CRLF-->
    mapBean.setMap(map);
<!--CRLF-->
    
<!--CRLF-->
    mav.addObject(mapBean);
<!--CRLF-->
    
<!--CRLF-->
    return mav;
<!--CRLF-->
}
<!--CRLF-->

首先看看MapBean的代码,代码很简单就一个Map的属性。

package com.hoo.entity;
<!--CRLF-->

<!--CRLF-->

    
import java.util.HashMap;
<!--CRLF-->
import javax.xml.bind.annotation.XmlRootElement;
<!--CRLF-->
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
<!--CRLF-->
import com.hoo.util.MapAdapter;
<!--CRLF-->

<!--CRLF-->

    
@XmlRootElement
<!--CRLF-->
public class MapBean {
<!--CRLF-->
    private HashMap<string accountbean> map;</string>
<!--CRLF-->
    
<!--CRLF-->
    @XmlJavaTypeAdapter(MapAdapter.class)
<!--CRLF-->
    public HashMap<string accountbean> getMap() {</string>
<!--CRLF-->
        return map;
<!--CRLF-->
    }
<!--CRLF-->
    public void setMap(HashMap<string accountbean> map) {</string>
<!--CRLF-->
        this.map = map;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

上面的代码的getMap方法设置了XmlJavaTypeAdapter这个注解,注解里面的MapAdapter是我们自己实现的,而且还要构建一个MapElements数组元素。主要是继承XmlAdapter重写里面的几个方法完成的。

MapAdapter代码

package com.hoo.util;
<!--CRLF-->

<!--CRLF-->

    
import java.util.HashMap;
<!--CRLF-->
import java.util.Map;
<!--CRLF-->
import javax.xml.bind.annotation.adapters.XmlAdapter;
<!--CRLF-->
import com.hoo.entity.AccountBean;
<!--CRLF-->

<!--CRLF-->

    
/**
<!--CRLF-->
 * function:AccountBean 编组、解组的XmlAdapter
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-25 下午05:03:18
<!--CRLF-->
 * @file MyAdetper.java
<!--CRLF-->
 * @package com.hoo.util
<!--CRLF-->
 * @project WebHttpUtils
<!--CRLF-->
 * @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
 * @email hoojo_@126.com
<!--CRLF-->
 * @version 1.0
<!--CRLF-->
 */
<!--CRLF-->
public class MapAdapter extends XmlAdapter<mapelements map accountbean>&gt; {</mapelements>
<!--CRLF-->
    public MapElements[] marshal(Map<string accountbean> arg0) <span style="color: #0000ff">throws</span> Exception {</string>
<!--CRLF-->
        MapElements[] mapElements = new MapElements[arg0.size()];
<!--CRLF-->

<!--CRLF-->

    
        int i = 0;
<!--CRLF-->
        for (Map.Entry<string accountbean> entry : arg0.entrySet())</string>
<!--CRLF-->
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
<!--CRLF-->

<!--CRLF-->

    
        return mapElements;
<!--CRLF-->
    }
<!--CRLF-->

<!--CRLF-->

    
    public Map<string accountbean> unmarshal(MapElements[] arg0) <span style="color: #0000ff">throws</span> Exception {</string>
<!--CRLF-->
        Map<string accountbean> r = <span style="color: #0000ff">new</span> HashMap<string accountbean>();</string></string>
<!--CRLF-->
        for (MapElements mapelement : arg0)
<!--CRLF-->
            r.put(mapelement.key, mapelement.value);
<!--CRLF-->
        return r;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

MapElements代码

package com.hoo.util;
<!--CRLF-->

<!--CRLF-->

    
import javax.xml.bind.annotation.XmlElement;
<!--CRLF-->
import com.hoo.entity.AccountBean;
<!--CRLF-->

<!--CRLF-->

    
/**
<!--CRLF-->
 * function: MapElements
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-25 下午05:04:04
<!--CRLF-->
 * @file MyElements.java
<!--CRLF-->
 * @package com.hoo.util
<!--CRLF-->
 * @project WebHttpUtils
<!--CRLF-->
 * @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
 * @email hoojo_@126.com
<!--CRLF-->
 * @version 1.0
<!--CRLF-->
 */
<!--CRLF-->
public class MapElements {
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public String key;
<!--CRLF-->
    
<!--CRLF-->
    @XmlElement
<!--CRLF-->
    public AccountBean value;
<!--CRLF-->

<!--CRLF-->

    
    @SuppressWarnings("unused")
<!--CRLF-->
    private MapElements() {
<!--CRLF-->
    } // Required by JAXB
<!--CRLF-->

<!--CRLF-->

    
    public MapElements(String key, AccountBean value) {
<!--CRLF-->
        this.key = key;
<!--CRLF-->
        this.value = value;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

在浏览器中请求:http://localhost:8080/SpringMVC4View/jaxb2/view/doMapXMLJaxb2.do

结果如下:

?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--CRLF-->
mapBean>map>item>key>NO2/key>value>address>china/address>
<!--CRLF-->
brithday>brithday>2011-11-22/brithday>/brithday>
<!--CRLF-->
email>tom@125.com/email>id>2/id>name>tom/name>/value>/item>
<!--CRLF-->
item>key>NO1/key>value>address>北京/address>brithday>brithday>2010-11-22/brithday>/brithday>
<!--CRLF-->
email>email/email>id>1/id>name>jack/name>/value>/item>/map>
<!--CRLF-->
/mapBean>
<!--CRLF-->

总结,如果你想将一些Java的基本类型转换成XML。那么你得创建一个带getter、setter方法的JavaBean。然后在Bean的getter方法进行相应的Annotation注解即可完成转换。

三、 利用xStream转换XML

1、 xStream可以轻易的将Java对象转换成XML、JSON,Spring整合利用xStream转换xml。需要添加xStream相关的xstream-1.3.1.jar包。 如果你对xStream不上很了解,你可以先阅读这篇文章:

For csblogs:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

For csdn:http://blog.csdn.net/IBM_hoojo/archive/2011/04/22/6342386.aspx

2、 然后在dispatcher.xml中添加如下配置

-- xml视图,XStreamMarshaller,可以转换任何形式的java对象,需要添加xStream jar包 -->
<!--CRLF-->
bean name="xStreamMarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<!--CRLF-->
    property name="marshaller">
<!--CRLF-->
        bean class="org.springframework.oxm.xstream.XStreamMarshaller">  
<!--CRLF-->
               --  启用annotation -->
<!--CRLF-->
               property name="autodetectAnnotations" value="true"/>  
<!--CRLF-->
               -- 类名别名 -->
<!--CRLF-->
            property name="aliases">
<!--CRLF-->
                map>
<!--CRLF-->
                    -- Account这个类的别名就变成了myBeans,那么转换后的xml中就是myBeans -->
<!--CRLF-->
                    entry key="myBeans" value="com.hoo.entity.Account"/>
<!--CRLF-->
                /map>
<!--CRLF-->
            /property>
<!--CRLF-->
            -- 基本属性别名 -->
<!--CRLF-->
            property name="fieldAliases">
<!--CRLF-->
                map>
<!--CRLF-->
                    -- Account中的brithday这个属性 -->
<!--CRLF-->
                    entry key="com.hoo.entity.Account.brithday" value="生日"/>
<!--CRLF-->
                /map>
<!--CRLF-->
            /property>
<!--CRLF-->
           /bean>  
<!--CRLF-->
    /property>
<!--CRLF-->
/bean>
<!--CRLF-->

上次配置的参数有注释描述,还要没有配置的参数。如:annotatedClass、annotatedClasses是当没有配置启用annotation的时候,可以用这2个属性进行配置你指定的class启用annotation注解。streamDriver是配置驱动用的,默认可以不要驱动,你可以配置DomDriver、JSON相关的驱动。encoding是设置编码,关于XStreamMarshaller还要更多的参数配置和上面xStream 的博文中讲解的一样使用,只是通过配置,而博文中是直接在代码中写的。当然也可以通过annotation进行注解哦;如果你想了解更多xStream的用法,请你仔细阅读:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

3、 普通JavaBean转换XML

package com.hoo.controller;
<!--CRLF-->

<!--CRLF-->

    
import java.util.ArrayList;
<!--CRLF-->
import java.util.Date;
<!--CRLF-->
import java.util.HashMap;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import java.util.Map;
<!--CRLF-->
import org.springframework.stereotype.Controller;
<!--CRLF-->
import org.springframework.web.bind.annotation.RequestMapping;
<!--CRLF-->
import org.springframework.web.servlet.ModelAndView;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
import com.hoo.entity.AccountArray;
<!--CRLF-->
import com.hoo.entity.AccountBean;
<!--CRLF-->
import com.hoo.entity.Brithday;
<!--CRLF-->
import com.hoo.entity.DifferBean;
<!--CRLF-->
import com.hoo.entity.ListBean;
<!--CRLF-->
import com.hoo.entity.MapBean;
<!--CRLF-->
import com.hoo.entity.MoreBean;
<!--CRLF-->
import com.hoo.entity.User;
<!--CRLF-->

<!--CRLF-->

    
/**
<!--CRLF-->
 * function:Jaxb2MarshallingView 视图,利用Jaxb2进行Java对象到XML的转换技术
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午03:20:23
<!--CRLF-->
 * @file Jaxb2MarshallingViewController.java
<!--CRLF-->
 * @package com.hoo.controller
<!--CRLF-->
 * @project SpringMVC4View
<!--CRLF-->
 * @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
 * @email hoojo_@126.com
<!--CRLF-->
 * @version 1.0
<!--CRLF-->
 */
<!--CRLF-->
@Controller
<!--CRLF-->
@RequestMapping("/jaxb2/view")
<!--CRLF-->
public class Jaxb2MarshallingViewController {
<!--CRLF-->
    
<!--CRLF-->
    /*
<!--CRLF-->
     * MarshallingView Jaxb2Marshaller 需要配置转换成xml的java对象的Annotation
<!--CRLF-->
     */
<!--CRLF-->
    @RequestMapping("/doXMLJaxb2")
<!--CRLF-->
    public ModelAndView doXMLJaxb2View() {
<!--CRLF-->
        System.out.println("#################ViewController doXMLJaxb2View##################");
<!--CRLF-->
        ModelAndView mav = new ModelAndView("jaxb2MarshallingView");
<!--CRLF-->
        
<!--CRLF-->
        AccountBean bean = new AccountBean();
<!--CRLF-->
        bean.setAddress("address");
<!--CRLF-->
        bean.setEmail("email");
<!--CRLF-->
        bean.setId(1);
<!--CRLF-->
        bean.setName("haha");
<!--CRLF-->
        Brithday day = new Brithday();
<!--CRLF-->
        day.setBrithday("2010-11-22");
<!--CRLF-->
        bean.setBrithday(day);
<!--CRLF-->
        
<!--CRLF-->
        mav.addObject(bean);
<!--CRLF-->
        
<!--CRLF-->
        return mav;
<!--CRLF-->
    }
<!--CRLF-->
}
<!--CRLF-->

AccountBean上面的代码已经给出,这里就不重复了。值得说明的是xStream在ModelAndView中,直接用addObject方法添加时,有时候出现一些不是我们转换的对象的信息,一般是BindingResult的xml信息。解决办法就是设置addObject的key。Key设置为BindingResult.MODEL_KEY_PREFIX这样就可以了,代码上面已经给出。

在浏览器中请求:http://localhost:8080/SpringMVC4View/xStream/view/doXMLXStream.do

结果如下:

com.hoo.entity.AccountBean>id>1/id>name>haha/name>email>email/email>address>北京/address>
<!--CRLF-->
brithday>brithday>2010-11-22/brithday>/brithday>/com.hoo.entity.AccountBean>
<!--CRLF-->

4、 转换对象数组

代码如下:

/**
<!--CRLF-->
 * function:转换对象数组
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午06:19:40
<!--CRLF-->
 * @return
<!--CRLF-->
 */
<!--CRLF-->
@RequestMapping("/doMoreXMLXStream")
<!--CRLF-->
public ModelAndView doMoreXMLXStreamView() {
<!--CRLF-->
    System.out.println("#################ViewController doMoreXMLXStreamView##################");
<!--CRLF-->
    ModelAndView mav = new ModelAndView("xStreamMarshallingView");    
<!--CRLF-->
    Account[] accs = new Account[2];
<!--CRLF-->
    Account bean = new Account();
<!--CRLF-->
    bean.setAddress("北京");
<!--CRLF-->
    bean.setEmail("email");
<!--CRLF-->
    bean.setId(1);
<!--CRLF-->
    bean.setName("haha");
<!--CRLF-->
    Brithday day = new Brithday();
<!--CRLF-->
    day.setBrithday("2010-11-22");
<!--CRLF-->
    bean.setBrithday(day);
<!--CRLF-->
    accs[0] = bean;
<!--CRLF-->
    
<!--CRLF-->
    bean = new Account();
<!--CRLF-->
    bean.setAddress("上海");
<!--CRLF-->
    bean.setEmail("email");
<!--CRLF-->
    bean.setId(1);
<!--CRLF-->
    bean.setName("haha");
<!--CRLF-->
    day = new Brithday();
<!--CRLF-->
    day.setBrithday("2010-11-22");
<!--CRLF-->
    bean.setBrithday(day);
<!--CRLF-->
    accs[1] = bean;
<!--CRLF-->
    mav.addObject(accs);
<!--CRLF-->
    return mav;
<!--CRLF-->
}
<!--CRLF-->

在WebBrowser中请求http://localhost:8080/SpringMVC4View/xStream/view/doMoreXMLXStream.do

结果如下:

myBeans-array>myBeans>id>1/id>name>haha/name>email>email/email>
<!--CRLF-->
address>北京/address>生日>brithday>2010-11-22/brithday>/生日>/myBeans>
<!--CRLF-->
myBeans>id>1/id>name>haha/name>email>email/email>address>上海/address>
<!--CRLF-->
生日>brithday>2010-11-22/brithday>/生日>/myBeans>/myBeans-array>
<!--CRLF-->

结果中的myBeans、生日就是在dispatcher配置文件中重命名的对象属性名称。

5、 转换Map集合

/**
<!--CRLF-->
 * function:转换Map对象
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午06:19:48
<!--CRLF-->
 * @return
<!--CRLF-->
 */
<!--CRLF-->
@RequestMapping("/doDifferXMLXStream")
<!--CRLF-->
public ModelAndView doDifferXMLXStreamView() {
<!--CRLF-->
    System.out.println("#################ViewController doDifferXMLXStreamView##################");
<!--CRLF-->
    ModelAndView mav = new ModelAndView("xStreamMarshallingView");
<!--CRLF-->
    
<!--CRLF-->
    Account bean = new Account();
<!--CRLF-->
    bean.setAddress("广东");
<!--CRLF-->
    bean.setEmail("email");
<!--CRLF-->
    bean.setId(1);
<!--CRLF-->
    bean.setName("haha");
<!--CRLF-->
    Brithday day = new Brithday();
<!--CRLF-->
    day.setBrithday("2010-11-22");
<!--CRLF-->
    bean.setBrithday(day);
<!--CRLF-->
    
<!--CRLF-->
    User user = new User();
<!--CRLF-->
    user.setAddress("china GuangZhou");
<!--CRLF-->
    user.setAge(23);
<!--CRLF-->
    user.setBrithday(new Date());
<!--CRLF-->
    user.setName("jack");
<!--CRLF-->
    user.setSex(true);
<!--CRLF-->
    
<!--CRLF-->
    Map<string object> map = <span style="color: #0000ff">new</span> HashMap<string object>();</string></string>
<!--CRLF-->
    map.put("bean", bean);
<!--CRLF-->
    map.put("user", user);
<!--CRLF-->
    mav.addObject(map);
<!--CRLF-->
    return mav;
<!--CRLF-->
}
<!--CRLF-->

在WebBrowser中请求http://localhost:8080/SpringMVC4View/xStream/view/doDifferXMLXStream.do

结果如下:

map>entry>
<!--CRLF-->
string>bean/string>myBeans>id>1/id>name>haha/name>email>email/email>
<!--CRLF-->
address>广东/address>生日>brithday>2010-11-22/brithday>/生日>/myBeans>
<!--CRLF-->
/entry>entry>string>user/string>com.hoo.entity.User>name>jack/name>age>23/age>sex>true/sex>
<!--CRLF-->
address>china GuangZhou/address>brithday>2011-04-27 19:02:13.747 CST/brithday>/com.hoo.entity.User>
<!--CRLF-->
/entry>/map>
<!--CRLF-->

6、 转换List集合

/**
<!--CRLF-->
 * function:转换List对象
<!--CRLF-->
 * @author hoojo
<!--CRLF-->
 * @createDate 2011-4-27 下午06:20:02
<!--CRLF-->
 * @return
<!--CRLF-->
 */
<!--CRLF-->
@RequestMapping("/doListXMLXStream")
<!--CRLF-->
public ModelAndView doListXMLXStreamView() {
<!--CRLF-->
    System.out.println("#################ViewController doListXMLXStreamView##################");
<!--CRLF-->
    ModelAndView mav = new ModelAndView("xStreamMarshallingView");
<!--CRLF-->
    ListObject> beans = new ArrayListObject>(); 
<!--CRLF-->
    for (int i = 0; i  3; i++) {
<!--CRLF-->
        Account bean = new Account();
<!--CRLF-->
        bean.setAddress("北京#" + i);
<!--CRLF-->
        bean.setEmail("email" + i + "@12" + i + ".com");
<!--CRLF-->
        bean.setId(1 + i);
<!--CRLF-->
        bean.setName("haha#" + i);
<!--CRLF-->
        Brithday day = new Brithday();
<!--CRLF-->
        day.setBrithday("2010-11-2" + i);
<!--CRLF-->
        bean.setBrithday(day);
<!--CRLF-->
        beans.add(bean);
<!--CRLF-->
        
<!--CRLF-->
        User user = new User();
<!--CRLF-->
        user.setAddress("china GuangZhou 广州# " + i);
<!--CRLF-->
        user.setAge(23 + i);
<!--CRLF-->
        user.setBrithday(new Date());
<!--CRLF-->
        user.setName("jack#" + i);
<!--CRLF-->
        user.setSex(Boolean.parseBoolean(i + ""));
<!--CRLF-->
        beans.add(user);
<!--CRLF-->
    }
<!--CRLF-->
    
<!--CRLF-->
    mav.addObject(beans);
<!--CRLF-->
    return mav;
<!--CRLF-->
}
<!--CRLF-->

在WebBrowser中请求http://localhost:8080/SpringMVC4View/xStream/view/doListXMLXStream.do

结果如下:

list>
<!--CRLF-->
myBeans>id>1/id>name>haha#0/name>email>email0@120.com/email>address>北京#0/address>生日>
<!--CRLF-->
brithday>2010-11-20/brithday>/生日>/myBeans>
<!--CRLF-->
com.hoo.entity.User>name>jack#0/name>age>23/age>sex>false/sex>address>china GuangZhou 广州# 0/address>
<!--CRLF-->
brithday>2011-04-27 19:08:40.106 CST/brithday>/com.hoo.entity.User>
<!--CRLF-->
myBeans>id>2/id>name>haha#1/name>email>email1@121.com/email>address>北京#1/address>生日>
<!--CRLF-->
brithday>2010-11-21/brithday>/生日>/myBeans>
<!--CRLF-->
com.hoo.entity.User>name>jack#1/name>age>24/age>sex>false/sex>address>china GuangZhou 广州# 1/address>
<!--CRLF-->
brithday>2011-04-27 19:08:40.106 CST/brithday>/com.hoo.entity.User>
<!--CRLF-->
myBeans>id>3/id>name>haha#2/name>email>email2@122.com/email>address>北京#2/address>生日>
<!--CRLF-->
brithday>2010-11-22/brithday>/生日>/myBeans>
<!--CRLF-->
com.hoo.entity.User>name>jack#2/name>age>25/age>sex>false/sex>address>china GuangZhou 广州# 2/address>
<!--CRLF-->
brithday>2011-04-27 19:08:40.106 CST/brithday>/com.hoo.entity.User>/list>
<!--CRLF-->

总结,xStream相对jaxb2要简单些。而且相对比较灵活,可以轻易的转换Java普通类型。

下次会介绍castor转换XML、jibx转换XML、Jackson转换JSON 以及自定义Jsonlib视图转换Json。

分享到:
评论

相关推荐

    SpringMVC 使用JSON、XML视图

    SpringMVC 使用JSON、XML视图,json-lib jackson,xstream castor,jibx jaxb2

    sprjson,spring mvc的json和xml视图,dwr及静态资源等不同种类url整合

    spring mvc的json和xml视图,dwr及静态资源等不同种类url整合,对应博客教程地址: http://blog.csdn.net/qgmzzn1/article/details/8465969

    springMVC rest风格视图解析

    springMVC spring mybatis rest风格架构 根据请求的后缀名 解析成json 或者 xml格式的数据

    SpringMVCSetup:Spring MVC初始项目。 它包含基本的json,xml视图解析器

    SpringMVC设置 Spring MVC初始项目。 它包含基本的json,xml视图解析器

    SpringMVC示例

    303数据校验、错误消息的显示及国际化、Ajax返回JSON、使用HttpMessageConverter、国际化_通过超链接切换中英文、文件上传、自定义的拦截器、拦截器的零Xml配置、异常处理(ExceptionHandler注解、 ...

    SpringMVC+Jquery实现Ajax功能

    Ajax:异步的JavaScript和Json(这里XML改为了Json); 作用:用于完成网页局部刷新功能(修改少量数据只用局部刷新,不用再整个网页重新加载); 二、SpringMVC和Jquery的简单介绍 SpringMVC:是基于Spring的一个子...

    maven-framework-project:基于maven的多框架和多视图融合技术(Struts1,Struts2,Spring,SpringMVC,Hibernate,Ibatis,MyBatis,Spring Data JPA,DWR)

    速度视图,freemarker视图,pdf视图,excel视图,xml视图,jsonview等)。是一个综合性的项目。该项目后期会陆续集成一些好的框架进来一些说Spring Web Flow,Jbpm,WebService,Compass,Solr,nutch等。总之是一个...

    j2ee-framework

    页面展现这里使用Struts1、Struts2、SpringMVC(jsp视图、velocity视图、freemarker视图、pdf视图、excel视图、xml视图、json视图等)。是一个综合性的项目。 该项目后期会陆续集成一些好的框架进来比如说Spring Web...

    SpringMVC Employee Demo

    driven配置、InitBinder注解、数据的格式化、JSR303数据校验、错误消息的显示及国际化、Ajax返回JSON、使用HttpMessageConverter、国际化_通过超链接切换中英文、文件上传、自定义的拦截器、拦截器的零Xml配置、异常...

    spring mvc 3.2 参考文档

    您可以直接与基于呈现技术的模板 (如 JSP、 Velocity和 Freemarker )集成或直接生成 XML、 JSON、 Atom和许多其他类型的内容。模型map被转化为合适的格式,如JSP request attributes或是 Velocity template model。

    spring_MVC源码

    -- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --&gt; 19. *.do&lt;/url-pattern&gt; 20. &lt;/servlet-mapping&gt; 21. &lt;welcome-file-list&gt; 22. &lt;welcome-file&gt;index.jsp...

    sprigmvc图文总结

    前端控制器(DispatcherServlet):接收请求,响应结果,返回可以是json,String等数据类型,也可以是页面(Model)。 处理器映射器(HandlerMapping):根据URL去查找处理器,一般通过xml配置或者注解进行查找。 ...

    【JeeSpringCloud v3.2.4】后台权限管理系统+互联网云快速开发框架+微服务分布式代码生成

    微服务/集群(nignx) 支持REST风格远程调用(HTTP + JSON/XML):基于非常成熟的Spring Boot框架,在Spring Boot Spring Cloud中实现了REST风格(HTTP + JSON/XML)的远程调用,以显着简化企业内部的跨语言交互,同时...

    Spring MVC 3.0实战指南.ppt

    输出XML和JSON 使用HttpEntity&lt;T&gt;/ResponseEntity&lt;T&gt; 目录 数据绑定机理 数据类型转换 PropertyEditor依然有效 强大的ConversionService,让很多梦想成真 基于ConversionService体系,定义自定义的类型转换器 格式化...

    【JeeSpringCloud v3.2.4】后台权限管理系统+互联网云快速开发框架+微服务分布式代码生成.zip

    微服务/集群(nignx) 支持REST风格远程调用(HTTP + JSON/XML):基于非常成熟的Spring Boot框架,在Spring Boot Spring Cloud中实现了REST风格(HTTP + JSON/XML)的远程调用,以显着简化企业内部的跨语言交互,同时...

    JeeSpringCloud后台权限管理系统-其他

    微服务/集群(nignx) 支持REST风格远程调用(HTTP + JSON/XML):基于非常成熟的Spring Boot框架,在Spring Boot Spring Cloud中实现了REST风格(HTTP + JSON/XML)的远程调用,以显著简化企业内部的跨语言交互,同时...

Global site tag (gtag.js) - Google Analytics