在JavaScript / jquery中调用bean方法?

时间:2014-05-28 12:43:00

标签: javascript jquery jsp java-ee javabeans

我需要在JavaScript和/或jQuery中调用bean方法,并且必须根据方法返回的值做出决定。

我们怎么做?

1 个答案:

答案 0 :(得分:1)

为了让JavaScript和Java Servlet能够交谈,正如你的建议你需要一个AJAX调用,你可以使用jQuery。

首先,设置一个新的Servlet,它将充当各种AJAX Web服务。我们将保持简单,所以只需实现doGet()方法来处理HTTP GET请求。在该GET方法中,查看特定参数的查询字符串。

示例:

myServlet?myArgument1=value1

(确保您的web.xml在此示例中将Servlet映射到/ myServlet)

在Java代码中处理请求(从bean中获取值),然后基于此构建JSON响应。例如,您可以返回:

{ "response": "my value" }

Java方面已经完成。

在JavaScript方面,您需要启动$ .getJSON()查询。

您可以通过以下方式执行此操作:

var myRequest = $.getJSON("myServlet?myArgument1=" + value1, 
    function(data) 
    {
        console.log( "success" );
        // Process the 'data', which is the JSON response.
        var returnedJson = JSON.parse(data);
        var value = returnedJson.response; // now equals "my value"
        // ...
    })     
    .fail(function() 
    {
        // Handle errors here
        console.log( "error" );
    })
    .always(function() 
    {
        // If you need to do something whether the request was success or fail,
        // do it here.
        console.log( "complete" );
    });

在我看来,这将是最直接的方式。如果您正在寻找一个可以轻松解析或创建JSON的Java库,而不是“硬编码”它,您可以查看json-smart。 https://code.google.com/p/json-smart/