2013-08-23 51 views
4

我會嘗試儘可能具體。獲取json返回類型和html返回相同的動作

我有一個Action有兩個方法,一個是通過ajax調用,另一個是通過常規提交調用。

重點是無法從常規提交中獲取請求,我只獲取操作屬性。

public class ClientAction{ 

    @SMDMethod 
    public Map<String, Object> findClient(String myParam){ 
    ... 
    } 

    public String saveClient(){    
     Map<String, String[]> parameterMap = this.getRequest().getParameterMap(); 
    } 
} 

getRequest from saveClient方法返回null !!!但爲什麼???我沒有@SMDMethod

聲明它和這裏是struts.xml中

<action name="client" class="myCompany.ClientAction"> 
     <interceptor-ref name="customJSON"><param name="enableSMD">true</param></interceptor-ref> 
     <result type="json"><param name="enableSMD">true</param></result> 
</action> 

我做了所有的其他聲明。我曾經有兩個單獨的類,每個方法都有一個,但ClientAction和ClientActionJSON的可維護性並不容易。

有關如何在同一個類中同時使用兩種方法(一種ajax和其他方法)的任何想法。

+0

使用_action_批註,並使用嵌套的_result_批註指定結果類型。 XML也是一樣的。當然,這將兩個動作放到一個類中......語義的輕微改變,在這種情況下不需要「enableSMD」。我想你可能需要在struts2-conventions-plugin(我總是添加它,所以不確定)。 – Quaternion

+0

你的意思是這樣的嗎? true '和另外一個像'<動作名稱=」 客戶」類= 「myCompany.ClientAction」>' – Sergio1978

+1

你還在使用enableSMD使之不我的意思是... – Quaternion

回答

2

我會馬上考慮寫一個樣本:

<action name="xclient" class="myCompany.ClientAction" method="jsonMethod"> 
    <result type="json"></result> 
</action> 
<action name="yclient" class="myCompany.ClientAction" method="htmlMethod"> 
    <result type="dispatcher">/pages/y.jsp</result> 
</action> 

現在只需在您CLIENTACTION創建兩種方法jsonMethod()& htmlMethod(),一個處理JSON和另一個HTML響應。

[編輯]

我又看了一遍,似乎像你只需要一個動作,以及後來乾脆考慮使用字段(請求參數)來決定返回類型。

public String execute(){ 
    //..Other code 
    if(returntype.equals("json")){ 
     return "jsonresult"; 
    } 
    else{ 
     return "htmlresult"; 
    } 
} 

<action name="client" class="myCompany.ClientAction" method="jsonMethod"> 
    <result name="jsonresult" type="json"></result> 
    <result name="htmlresult" type="dispatcher">/pages/y.jsp</result> 
</action> 

在上面,我認爲,returntype是你與每個請求指定預計什麼回報發送沿字符串變量。您可以簡單地將它隱藏在表單提交中並將其設置在ajax請求中。

+0

其實我正在維護一個項目。我的ajax/json函數必須因爲框架而返回一個Map,但到目前爲止,所有這些函數都在JsonAction.java中。 但謝謝你的迴應,如果不喜歡如何分割商業科目的文件。所以現在我有ClientAction.java和所有的json和非json方法。 正如@coding_idiot在他的xml片段中所考慮的那樣,它是一個json或非json方法。 – Sergio1978