首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >struts2和jaxb用于2.0.x以上版本的struts2

struts2和jaxb用于2.0.x以上版本的struts2
EN

Stack Overflow用户
提问于 2013-05-22 08:40:55
回答 1查看 377关注 0票数 1

是否有像struts2-jaxb-plugin这样的插件,适用于高于2.0.x版本的struts2?

新版本的struts2不再在类com.opensymphony.xwork2.ActionContext上使用get(对象o)。

如果有更好的方法来使用struts2实现xml结果,可以自由地指出正确的方向。

否则,我正在考虑编写我自己的编组拦截器和jaxb结果类型,就像在struts2-jaxb插件中所发生的那样。

现有版本:

  • struts2 : 2.3.14
  • jaxb-api : 2.2.9
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-22 13:07:50

刚写了我自己的jaxb结果类型。比我想象的要容易得多。

把它留给那些寻找类似东西的人:

代码语言:javascript
复制
import java.io.IOException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;

public class JaxbResult implements Result {
    private static final long serialVersionUID = -5195778806711911088L;
    public static final String DEFAULT_PARAM = "jaxbObjectName";

    private String jaxbObjectName;

    public void execute(ActionInvocation invocation) throws Exception {
        Object jaxbObject = getJaxbObject(invocation);
        Marshaller jaxbMarshaller = getJaxbMarshaller(jaxbObject);
        Writer responseWriter = getWriter();

        setContentType();
        jaxbMarshaller.marshal(jaxbObject, responseWriter);
    }

    private Writer getWriter() throws IOException {
        return ServletActionContext.getResponse().getWriter();
    }

    private Marshaller getJaxbMarshaller(Object jaxbObject) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(jaxbObject.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        return jaxbMarshaller;
    }

    private Object getJaxbObject(ActionInvocation invocation) {
        ValueStack valueStack = invocation.getStack();

        return valueStack.findValue(getJaxbObjectName());
    }

    private void setContentType() {
        ServletActionContext.getResponse().setContentType("text/xml");
    }

    public String getJaxbObjectName() {
        return jaxbObjectName;
    }

    public void setJaxbObjectName(String jaxbObjectName) {
        this.jaxbObjectName = jaxbObjectName;
    }
}

struts-xml中的配置如下所示:

代码语言:javascript
复制
<result-types>
    <result-type name="jaxb" class="JaxbResult" />
</result-types>

<action name="testaction" class="TestAction">
    <result name="success" type="jaxb" >jaxbObject</result>
</action>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16687232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档