2014-01-25 73 views
1

我正在使用Struts2-json-plugin-2.3.16和相同版本的框架。我從JSON得到一個空的響應。如何在Struts 2中使用JSON-RPC

JavaScript/jQuery函數。

var timeout; 
var request; 

function getUsers() 
{ 
    if(!request) 
    {      
     request = $.ajax({ 
      datatype:"json", 
      type: "GET", 
      contentType: "application/json; charset=utf-8", 
      url: "testJsonAction.action", 
      success: function(response) 
      { 
       var user= response.user; 
       alert(user); 
      }, 
      complete: function() 
      { 
       timeout = request = null; 
      }, 
      error: function(request, status, error) 
      { 
       if(status!=="timeout"&&status!=="abort") 
       { 
        alert(status+" : "+error); 
       } 
      } 
     }); 
     timeout = setTimeout(function() { 
      if(request) 
      { 
       request.abort(); 
       alert("The request has been timed out."); 
      } 
     }, 30000); 
    } 
} 

當單擊按鈕時調用此函數。

<s:form namespace="/admin_side" action="Test" validate="true" id="dataForm" name="dataForm"> 

    <input type="button" name="btnUser" id="btnUser" value="Click" onclick="getUsers();"/> 

</s:form> 

動作類:

@Namespace("/admin_side") 
@ResultPath("/WEB-INF/content") 
@ParentPackage(value = "json-default") 
public final class TestAction extends ActionSupport { 

    private User user; 
    private static final long serialVersionUID = 1L; 

    public TestAction() { 
    } 

    @JSON(name = "user") 
    public User getUser() { 
     return user; 
    } 

    public void setUser(User user) { 
     this.user = user; 
    } 

    @Action(value = "testJsonAction", 
    results = { 
     @Result(type = "json", name = ActionSupport.SUCCESS, params = {"enableSMD", "true", "enableGZIP", "true", "excludeNullProperties", "true"})}) 
    public String executeAction() throws Exception { 
     try { 
      user = new User(); 
      user.setName("Tiny"); 
      user.setDob(new SimpleDateFormat("dd-MMM-YYYY").parse("29-Feb-2000")); 
      user.setLocation("India"); 
     } catch (ParseException ex) { 
      Logger.getLogger(TestAction.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     return ActionSupport.SUCCESS; 
    } 

    @Action(value = "Test", 
    results = { 
     @Result(name = ActionSupport.SUCCESS, location = "Test.jsp"), 
     @Result(name = ActionSupport.INPUT, location = "Test.jsp")}, 
    interceptorRefs = { 
     @InterceptorRef(value = "defaultStack", params = {"params.acceptParamNames", "", "params.excludeMethods", "load", "validation.validateAnnotatedMethodOnly", "true"})}) 
    public String load() throws Exception { 
     return ActionSupport.SUCCESS; 
    } 
} 

User類:

public class User 
{ 
    private String name; 
    private Date dob; 
    private String location; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public Date getDob() { 
     return dob; 
    } 

    public void setDob(Date dob) { 
     this.dob = dob; 
    } 

    public String getLocation() { 
     return location; 
    } 

    public void setLocation(String location) { 
     this.location = location; 
    } 
} 

TestAction類的executeAction()方法被調用,點擊指定的按鈕時,但我不明白一個用戶對象作爲JSON響應。它似乎總是空的。

這裏缺少什麼?除了Struts2-json-plugin-2.3.16庫之外是否還需要其他庫?


使用像這種情況下的直接鏈接,http://localhost:8080/TestStruts/admin_side/testJsonAction.action,我得到以下字符串。

{"methods":[],"serviceType":"JSON-RPC","serviceUrl":"\/TestStruts\/admin_side\/testJsonAction.action","version":".1"} 
+0

您是否想對請求使用JSON-RPC? –

+0

對不起,我不明白。我第一次看到'JSON-RPC'! – Tiny

+0

'enableSMD = true'用於[JSON-RPC](http://en.wikipedia.org/wiki/JSON-RPC)請求。它允許將對象傳遞給動作來執行方法並返回結果,因此可以在客戶端和服務器上使用同一個對象,一切看起來都是透明的。 –

回答

1

你應該做的,如果你需要使用JSON-RPC與Struts2的:

配置的行動,返回JSON-RPC服務

@Action(value = "testJsonAction", 
    results = @Result(type = "json", params = {"enableSMD", "true"}), 
    interceptorRefs = @InterceptorRef(value="json", params={"enableSMD", "true"})) 
public String executeAction() throws Exception { 
    return SUCCESS; 
} 

創建方法

@SMDMethod 
public User getUser() { 

    user = new User(); 
    user.setName("Tiny"); 
    user.setLocation("India"); 

    try { 
     user.setDob(new SimpleDateFormat("dd-MMM-YYYY").parse("29-Feb-2000")); 
    } catch (ParseException ex) { 
     Logger.getLogger(TestAction.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    return user; 
} 

現在,您需要一個JSON-RPC客戶端發出請求,或者嘗試$.ajax

<s:url var="testJsonUrl" action="testJsonAction"/> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
    $("#btnUser").click(function(){ 
     $.ajax({ 
     type:"POST", 
     url: "<s:property value='#testJsonUrl'/>", 
     dataType:"json",    
     data: JSON.stringify({jsonrpc:'2.0', method:'getUser', id:'jsonrpc'}), 
     contentType: "application/json-rpc; charset=utf-8", 
     success: function(response) { 
      var user= response.result; 
      alert(JSON.stringify(user)); 
     } 
     }); 
    }); 
    }); 
</script> 
+0

我已經嘗試完全一樣的東西,但答案總是空的。可能是,我會有下一個問題:)。它沒有'JSON-RPC'。 – Tiny

+0

今天早上我用工作解決方案更新了代碼,我沒有檢查與'User'初始化有關的'ParseException'。 –

+0

不引發解析異常。我收到這個字符串作爲響應,'{「methods」:[{「name」:「getUser」,「parameters」:[]}],「serviceType」:「JSON-RPC」,「serviceUrl」:「\/TestStruts \/admin_side \ /testJsonAction.action「,」version「:」。1「}'在地址欄中直接鏈接。 – Tiny