如何在Struts 2中使用JSON-RPC

时间:2014-01-25 18:22:54

标签: java jquery json struts2 struts2-json-plugin

我正在使用Struts2-json-plugin-2.3.16和相同版本的框架。我从JSON得到一个空的回复。

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;
    }
}

当单击给定按钮但我没有将用户对象作为JSON响应时,将调用executeAction()类中的TestAction方法。它似乎总是空的。

这里缺少什么?除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"}

1 个答案:

答案 0 :(得分:1)

如果你需要在Struts2中使用JSON-RPC,你应该怎么做:

配置返回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>