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 AJA开发者_如何转开发X itself..
What is the recommended approach?
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.
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.
精彩评论