2011-06-08 40 views
0

我希望得到一些我必須實現的幫助。非常感謝你提前。struts2 + jquery + ajax調用:從動作返回xml文件

我在做一個web應用程序與struts2。現在我需要實現一種方式,用戶可以通過獲得一個xml文件,但不需要重新加載網頁

JSP,與jquery,我已經實現調用Ajax(一個動作)這樣的:

$(function() { 
[...] 
$("#getXML").click(function() { 
     [...] 
     $.ajax({ 
      type : "POST", 
      url : "Servlets.action", 
      data : "id="+$id+"&objects="+$objectsMap+"&relations="+$linesMap+"&inputs="+$inputs+"&option=2", 
      dataType : "xml", 
      success : function(data) { 
         //¿?? 
         } 
     }); 
     }); }); 

我已經定義在struts.xml中構造的動作的Servlet。

而且行動現在看起來是這樣的:

public class Servlets extends ActionSupport implements SessionAware, ServletRequestAware{ 

private ApplicationDao applicationDao; 
public void setServletRequest(HttpServletRequest request) { 
    this.request = request; 
} 

public String execute() throws Exception { 
    [...] 
    if (request.getParameter("option").equals("1")) { 
     [...] 
    } 
    if (request.getParameter("option").equals("2")) { 
     [...] 
     File xml = new File(id+".xml"); 
     XMLcreator.createXML(id,project,xml); 
     //I want to return the File object "xml" to the user through the jquery 
    } 
    else { 
     return ERROR; 
    } 
    return SUCCESS; 
} } 

我希望有人告訴我我怎麼能返回File對象「XML」到已下令它的用戶。

非常感謝你,

Aleix

回答

1

首先,我會鼓勵你從來沒有 「返回錯誤」。更好的方法是拋出異常並讓ExceptionMappingInterceptor映射到您的錯誤頁面。

至於你的問題,你希望你的Ajax動作返回一些XML。一種方法是通過getFile()方法公開File對象,然後創建一個JSP來顯示它(如XML)。

例如

public class Servlets extends ActionSupport ... { 
    private File file; 

    public String execute() throws Exception { 
    [...] 
    if (request.getParameter("option").equals("2")) { 
     [...] 
     file = new File(id + ".xml"); 
     XMLcreator.createXML(id, project, file); 
    } else { 
     throw new RuntimeException("Your error message here."); 
    } 
    return SUCCESS; 
    } 

    public File getFile() { 
    return file; 
    } 
} 

然後,你的JSP將類似於這樣(不知道你的具體XML的樣子):

<?xml version="1.0" encoding="UTF-8"?> 
<%@ page contentType="text/xml;charset=UTF-8" language="java" %> 
<file hidden="${action.file.hidden}"> 
    <name>${action.file.name}</name> 
</file> 

${action.file}指的是你的行動getFile()方法。

然後只要確保JSP被映射到SUCCESS結果。

處理此問題的另一種方法是創建自定義結果類型。