在Struts2中使用JSON-RPC [英] Using JSON-RPC in Struts2

查看:168
本文介绍了在Struts2中使用JSON-RPC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下JavaScript/jQuery函数进行远程过程调用.

I use the following JavaScript/jQuery function to make a remote procedure call.

<script src="../js/jquery-1.8.0.min.js" type="text/javascript"></script>
<s:url var="testJsonUrl" action="testJsonAction"/>

var timeout;
var request;

$(document).ready(function(){
    $("#btnUser").click(function(){
        if(!request)
        {
            request = $.ajax({
                datatype:"json",
                type: "GET",
                data: JSON.stringify({jsonrpc:'2.0', method:'getUser', id:'jsonrpc'}),
                contentType: "application/json-rpc; charset=utf-8",
                url: "<s:property value='#testJsonUrl'/>",
                success: function(response)
                {
                    var user = response.result;
                    alert(JSON.stringify(user));  //Always alerts "undefined".
                },
                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);
        }
    });
});

单击以下按钮时,将调用上述函数.

The above function is called, when a button is clicked as follows.

<s:form namespace="/admin_side" action="Test" validate="true" id="dataForm" name="dataForm">
    <input type="button" name="btnUser" id="btnUser" value="Click"/>
</s:form>

要在其中调用该方法的动作类如下.

The action class in which the method is to be invoked is as follows.

import com.opensymphony.xwork2.ActionSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.json.annotations.SMDMethod;
import util.User;

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

    public TestAction() {}

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

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

    @Action(value = "testJsonAction",
    results = {
        @Result(type = "json", params = {"enableSMD", "true", "excludeNullProperties", "true"})},
    interceptorRefs = {
        @InterceptorRef(value = "json", params = {"enableSMD", "true"})})
    public String executeAction() throws Exception {
        return 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 {
        //This method is just needed to return a view on page load.
        return ActionSupport.SUCCESS;
    }
}

User类:

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

    //Setters & getters.
}

当单击给定按钮但未单击时,预期将调用用@SMDMethod注释的getUser()方法(在动作类TestAction中).

The getUser() method (in the action class TestAction) annotated with @SMDMethod is expected to be invoked, when the given button is clicked but it does not.

jQuery函数success处理程序中的这一行alert(JSON.stringify(user));始终会警告undefined.

This line alert(JSON.stringify(user)); in the success handler of the jQuery function always alerts undefined.

在地址栏中使用直接链接,例如,

Using a direct link in the address bar like,

http://localhost:8080/TestStruts/admin_side/testJsonAction.action

返回以下字符串.

{
    "methods": [{
        "name": "getUser",
        "parameters": []
    }],

    "serviceType": "JSON-RPC",
    "serviceUrl": "\/TestStruts\/admin_side\/testJsonAction.action",
    "version": ".1"
}

这里缺少什么? JSON-RPC为什么不起作用?

What is missing here? Why does not JSON-RPC work?

PS:我正在将Struts2-json-plugin-2.3.16与相同版本的框架一起使用.

PS : I'm using Struts2-json-plugin-2.3.16 with same version of the framework.

推荐答案

使用JSON-RPC时是否只有POST请求是强制性的?

Is it mandatory to have only the POST request while using JSON-RPC?

是的,它仅适用于POST请求

yes, it only works with POST request

includeProperties无效

如果

includePropertiesjson拦截器的参数,则它会生效.不要混淆与json结果一起使用的参数的名称.

includeProperties has effect if it's a parameter to json interceptor. Don't confuse the name of parameter used with json result.

在这种情况下,字段dob应该已排除

在这种情况下,最好使用excludeProperties参数来拦截,就像这样

In this case better to use excludeProperties parameter to interceptor, like this

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

这篇关于在Struts2中使用JSON-RPC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆