2012-04-27 28 views
1

我想在strurts2中的xml類型的javascript中獲得響應。 在我的動作類中,我創建了一個xml,我試圖在java腳本中獲取它。 我在動作類代碼 -如何在struts2中獲得xml作爲響應

public String populateXML(){ 
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder documentBuilder; 

    String root = "menuTree"; 
    File file = new File(this.getServletRequest().getRealPath("/xml/xmlmenutree2.xml")); 

    documentBuilder = documentBuilderFactory.newDocumentBuilder(); 
    Document document1 = documentBuilder.newDocument(); 

    Element rootElement = null; 
    rootElement = document1.createElement(root); 
    document1.appendChild(rootElement); 

    TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
    Transformer transformer = transformerFactory.newTransformer(); 

    DOMSource source = new DOMSource(document1); 
    StreamResult result = new StreamResult(file); 

    transformer.transform(source, result); 
    return SUCCESS; 
} 

這將創建一個在我的磁盤上的XML文件。並在我的JavaScript我訪問它像 -

$(document).ready(function() { 
    var options = { 
    xmlUrl : 'xml/xmlmenutree2.xml' 

}; 
    $('#xmlMenuTree').xmltree(options); 
} 

其中xmlMenuTree是我的div id在jsp。 and structs xml-

<action name="fileManagement" class="com.amit.MyAction" method="populateXML"> 
    <result name="success" type="tiles">filemanagement</result> 
</action> 

這工作正常。但我實際上希望將xml設置爲響應而不是將其保存在我的磁盤中。 是否可以在strurts2中進行設置?提前謝謝你。 Amit

回答

0

將xml放入響應對象並通過適當的標籤訪問視圖層...簡單。 我認爲這可能會節省您的時間。

0

操作:

public class MyAction extends ActionSupport { 
    //Generate xml like InputStream and put it here 
    private InputStream myXmlStream;  

行動定義:

<action name="MyAction" class="mypackage.MyAction"> 
    <result type="stream"> 
    <!-- Struts will take InputStream from this variable and send it as response--> 
    <param name="myXmlStream">text/plain</param> 
    <!-- Set fake filename--> 
    <param name="contentDisposition">filename="xmlmenutree2.xml"</param> 
    </result> 
</action 
+0

不知道'myXmlStream'參數是什麼,但它不會是text/plain的,如果它是一個XML文檔,它會對於'contentType',可以是'text/xml'或'application/xml'或其他東西。 'inputName'設置流屬性名稱,默認爲'inputStream'。 – 2012-04-27 12:12:39

+0

謝謝戴夫..我與我測試..我一定會讓你知道! :) – Amit 2012-04-27 16:02:18

相關問題