Domanda

Is there some kind of plugin like the struts2-jaxb-plugin that works for versions of struts2 higher than version 2.0.x?

The newer versions of struts2 no longer have the get(Object o) on the Class com.opensymphony.xwork2.ActionContext .

If there is a better way of accomplishing an xml result with struts2, feel free to point me in the right direction.

Otherwise, i'm thinking along the way of writing my own marshalling interceptor and jaxb result-type like what happened in the struts2-jaxb-plugin.

current versions:

  • struts2 : 2.3.14
  • jaxb-api : 2.2.9
È stato utile?

Soluzione

Just wrote my own jaxb result-type. It was easier than i thought it would be.

leaving it below for those looking for something similar:

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;
    }
}

The configuration in the struts-xml looks something like this:

<result-types>
    <result-type name="jaxb" class="JaxbResult" />
</result-types>

<action name="testaction" class="TestAction">
    <result name="success" type="jaxb" >jaxbObject</result>
</action>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top