0

What are the various options to call a "specific" Java method from Javascript and have callback, etc?

E.g. One i know is using DWR..But wanted to know if there are any other libraries that can be used OR if this can be done by AJAX itself..

What is the recommended approach?

2 Answers 2

2

Put simply, with the possible exception of a Java applet running in the same page context as the JavaScript, there is no way for JavaScript to directly call a Java method, or vice-versa. DWR isn't calling any Java methods directly from JavaScript, it's sending an AJAX request to the server and using its own intermediate layer to instrument the request and response processing such that it looks as if it is calling Java methods.

But anyways, the typical approach for getting JavaScript code in the client and Java code on the server to talk to one another is to define an API on the server that is exposed to the client. The client can then make requests (using AJAX or whatever other mechanism you prefer) using the exposed API. The client isn't calling any Java methods directly, instead it's sending a request to a given URL on the server, which gets mapped back to some bit of Java code. Most popular JavaScript frameworks provide convenience methods for simplifying AJAX request handling and callbacks.

If for some reason you want functionality equivalent to being able to call an arbitrary method in an arbitrary class and have the result returned to you, then you could define an API method that takes as parameters a class name and a method name and then uses reflection to perform the method invocation. This would probably be very close to what the server-side portion of DWR is doing.

Sign up to request clarification or add additional context in comments.

2 Comments

Everything good except for the REST ;) it doesn't necessarily have to be RESTful.
@Murali VP - True enough. Fixed.
0

I know you can do this when using Mozilla Rhino, but I'm guessing that you're talking about a browser run-time environment, so maybe this response isn't very helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.