Reputation: 5977
I need to call a bean method in JavaScript and/or jQuery,and have to make decisions depending upon the value returned by method.
How can we do this?
Upvotes: 1
Views: 965
Reputation: 773
In order for JavaScript and a Java Servlet to be able to talk, as you suggested you will need an AJAX call, which you can do with jQuery.
First, setup a new Servlet which will act as an AJAX web service of sorts. We'll keep it simple, so just implement the doGet() method to handle HTTP GET requests. In that GET method, have a look at the query string for specific arguments.
Example:
myServlet?myArgument1=value1
(Make sure your web.xml maps your Servlet to /myServlet in this example)
Process the request in your Java code (get the value from your bean), then build a JSON response based on that. For instance, you could return:
{ "response": "my value" }
The Java side is done.
On the JavaScript side, you will need to launch a $.getJSON() query.
You would do this in the following way:
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" );
});
In my opinion that would be the most straightforward way to do it. If you're looking for a Java library that will easily let you parse or create JSON, instead of 'hard-coding' it, you can have a look at json-smart. https://code.google.com/p/json-smart/
Upvotes: 1