是否有类似struts2-jaxb-plugin的插件适用于版本高于2.0.x的struts2版本?
较新版本的struts2不再具有类com.opensymphony.xwork2.ActionContext上的get(Object o)。
如果有更好的方法来完成struts2的xml结果,请随意指向正确的方向。
否则,我正在考虑编写自己的编组拦截器和jaxb结果类型,就像struts2-jaxb-plugin中发生的一样。
当前版本:
答案 0 :(得分:1)
刚写了我自己的jaxb结果类型。它比我想象的要容易。
将它留在下面寻找类似的东西:
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中的配置如下所示:
<result-types>
<result-type name="jaxb" class="JaxbResult" />
</result-types>
<action name="testaction" class="TestAction">
<result name="success" type="jaxb" >jaxbObject</result>
</action>