سؤال

I'm using Struts2-json-plugin-2.3.16 with the same version of the framework. I get an empty response from JSON.

The JavaScript/jQuery function.

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

This function is called, when a button is clicked.

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

The action class:

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

The User class:

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

The executeAction() method in the TestAction class is invoked, when the given button is clicked but I do not get a user object as a JSON response. It always seems to be empty.

What is missing here? Does it require other libraries in addition to the the Struts2-json-plugin-2.3.16 library?


Using a direct link like in this case, http://localhost:8080/TestStruts/admin_side/testJsonAction.action, I get the following string.

{"methods":[],"serviceType":"JSON-RPC","serviceUrl":"\/TestStruts\/admin_side\/testJsonAction.action","version":".1"}
هل كانت مفيدة؟

المحلول

What should you do if you need to use JSON-RPC with Struts2:

Configure action that returns JSON-RPC service

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

create a method

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

Now, you need a JSON-RPC client to make a request, or try $.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>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top