开发者

Options to call Java method from Javascript

开发者 https://www.devze.com 2023-03-17 01:30 出处:网络
What are the various options to call a \"specific\" Java method from Javascript and have callback, etc?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号