是否有像struts2-jaxb-plugin这样的插件,适用于高于2.0.x版本的struts2?
新版本的struts2不再在类com.opensymphony.xwork2.ActionContext上使用get(对象o)。
如果有更好的方法来使用struts2实现xml结果,可以自由地指出正确的方向。
否则,我正在考虑编写我自己的编组拦截器和jaxb结果类型,就像在struts2-jaxb插件中所发生的那样。
现有版本:
发布于 2013-05-22 13:07:50
刚写了我自己的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>https://stackoverflow.com/questions/16687232
复制相似问题