2013-05-22 68 views
1

是否有某種類似於struts2-jaxb-plugin的插件,適用於版本高於2.0.x的struts2版本?struts2和jaxb版本的struts2版本高於2.0.x

較新版本的struts2不再具有類com.opensymphony.xwork2.ActionContext上的get(Object o)。

如果有更好的方式用struts2實現xml結果,請隨意指向正確的方向。否則,我正在想寫我自己的編組攔截器和jaxb結果類型,就像struts2-jaxb-plugin中發生的那樣。

當前版本:

  • Struts2的:2.3.14
  • JAXB的API:2.2.9

回答

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>