使用高性能xml序列化框架jibx作为spring mvc的xml view

package org.springframework.web.servlet.view.xml;

import java.io.ByteArrayOutputStream;
import java.util.Map;

import javax.servlet.servletexception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.BeansException;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
import org.springframework.util.FilecopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class XmlMarshallerView extends AbstractView {

/**
* Default content type. Overridable as bean property.
*/
public static final String DEFAULT_CONTENT_TYPE = "application/xml";

private Marshaller marshaller;

private jibxMarshallerFactory jibxMarshallerFactory;

private String modelKey;

/**
* Constructs a new {@code MarshallingView} with no {@link Marshaller} set. The marshaller must be set after
* construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public XmlMarshallerView() {
setContentType(DEFAULT_CONTENT_TYPE);
setExposePathVariables(false);
}

/**
* Constructs a new {@code MarshallingView} with the given {@link Marshaller} set.
*/
public XmlMarshallerView(Marshaller marshaller) {
Assert.notNull(marshaller,"'marshaller' must not be null");
setContentType(DEFAULT_CONTENT_TYPE);
this.marshaller = marshaller;
setExposePathVariables(false);
}

public void setjibxMarshallerFactory(jibxMarshallerFactory jibxMarshallerFactory) {
this.jibxMarshallerFactory = jibxMarshallerFactory;
}

/**
* Sets the {@link Marshaller} to be used by this view.
*/
public void setMarshaller(Marshaller marshaller) {
Assert.notNull(marshaller,"'marshaller' must not be null");
this.marshaller = marshaller;
}

/**
* Set the name of the model key that represents the object to be marshalled. If not specified,the model map will be
* searched for a supported value type.
*
* @see Marshaller#supports(Class)
*/
public void setModelKey(String modelKey) {
this.modelKey = modelKey;
}

@Override
protected void initApplicationContext() throws BeansException {
if (marshaller == null && jibxMarshallerFactory == null) {
throw new RuntimeException("Property 'marshaller' or 'jibxMarshallerFactory',at least one is required");
}
}

@Override
protected void renderMergedOutputModel(Map<String,Object> model,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
Object toBeMarshalled = locatetoBeMarshalled(model);

if (toBeMarshalled == null) {
throw new servletexception("Unable to locate object to be marshalled in model: " + model);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
marshaller.marshal(toBeMarshalled,new StreamResult(bos));

setResponseContentType(request,response);
response.setContentLength(bos.size());

FilecopyUtils.copy(bos.toByteArray(),response.getoutputStream());
}

/**
* Locates the object to be marshalled. The default implementation first attempts to look under the configured
* {@linkplain #setModelKey(String) model key},if any,before attempting to locate an object of {@linkplain
* Marshaller#supports(Class) supported type}.
*
* @param model the model Map
* @return the Object to be marshalled (or {@code null} if none found)
* @throws servletexception if the model object specified by the {@linkplain #setModelKey(String) model key} is not
* supported by the marshaller
* @see #setModelKey(String)
*/
protected Object locatetoBeMarshalled(Map<String,Object> model) throws servletexception {
if (this.modelKey != null) {
Object o = model.get(this.modelKey);
if (o == null) {
throw new servletexception("Model contains no object with key [" + modelKey + "]");
}
checkMarshaller(o);
if (!this.marshaller.supports(o.getClass())) {
throw new servletexception("Model object [" + o + "] retrieved via key [" + modelKey +
"] is not supported by the Marshaller");
}
return o;
}
for (Object o : model.values()) {
if (o != null) {
checkMarshaller(o);
if (this.marshaller.supports(o.getClass())) {
return o;
}
}
}
return null;
}

/**
* check the marshaller is null or not
* @param object if the marshaller is null,will query from jibxMarshallerFactory by object
*/
protected void checkMarshaller(Object object) {
if (marshaller == null) {
marshaller = jibxMarshallerFactory.getjibxMarshaller(object.getClass());
}
}

}

这个类参考了spring mvc的MarshallingView。不同就是引入了jibxMarshallerFactory。因为jibx 要对每个要序列化的类进行字节码增强。如果使用xstream等xml框架则不需要使用这个类。当然使用也是可以的。可以直接使用MarshallingView。


package com.vteba.service.xml.jibx;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.oxm.jibx.jibxMarshaller;

/**
* jibxMarshaller Factory。
* @author yinlei
* date 2013-8-1 下午8:10:45
*/
public class jibxMarshallerFactory implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(jibxMarshallerFactory.class);
    private static final String BINDING_NAME = "Binding";

    private List<Class<?>> targetClassList;
    private Map<Class<?>, jibxMarshaller> jibxCache = new HashMap<Class<?>, jibxMarshaller>();

    @Override
    public void afterPropertiesSet() throws Exception {
        if (targetClassList != null) {
            for (Class<?> clazz : targetClassList) {
                jibxMarshaller jibxMarshaller = new jibxMarshaller();
                jibxMarshaller.setTargetClass(clazz);
                jibxMarshaller.setBindingName(BINDING_NAME);
                jibxMarshaller.afterPropertiesSet();
                jibxCache.put(clazz, jibxMarshaller);
            }
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("jibX映射目标类没有设置。运行时将无法获得jibxMarshaller实例。");
            }
        }
    }

    public List<Class<?>> getTargetClassList() {
        return targetClassList;
    }

    public void setTargetClassList(List<Class<?>> targetClassList) {
        this.targetClassList = targetClassList;
    }

    public jibxMarshaller getjibxMarshaller(Class<?> targetClass) {
        return jibxCache.get(targetClass);
    }
}

因为jibx对所有需要序列化的JavaBean都要事先注册,所以你要事先配置jibxMarshallerFactory,将所有要序列化的类都配置进去。

例如:

<bean id="jibxMarshallerFactory" class="com.vteba.service.xml.jibx.jibxMarshallerFactory">
        <property name="targetClassList">
            <list>
                <value>com.vteba.service.xml.jibx.Customer</value>
            </list>
        </property>
    </bean>

绝对原创,转载请注明出处。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇