Need to call a Java method whenever I click an HTML button. Basically I need to send over some text to a Java class when I click a button. I have tried applets to achieve this behaviour but didn't manage.
Thanks
UPDATE Solution: Java Web services
Your question involves multiple technologies. I will try to give you some direction towards all of them in steps.
When you write a Java class, it is deployed on the server side. When you write a JavaScript function, it is deployed on the client side.
The server side Java classes may be deployed as a web application in an application server (Apache tomcat for example), and exposed over a URL. The interface for doing so is to write what is known as a Servlet. A servlet is nothing but another Java class deployed on the same application server. This servlet class can invoke your Java method. (Note: There are other technologies (JSP or Java Server Pages, for example) which eventually get re-engineered to a servlet.)
There is abundant literature on how servlets work, but in short, once deployed in an application server, the code inside the servlet can be invoked when the application URL is invoked from a browser.
So, here are the steps:
http://localhost:8080/myapp/doSomethingdoXXX methods (for GET, POST, etc. operation).Having said the above steps, from JavaScript, you can invoke a URL and get a response using technologies like AJAX.
If your function does not return a value, but simply "does something", then you really do not care about the response, However, using AJAX, you can also check the status on the response to see if there were any exceptions that occurred while executing your function on the server side.
There is a better way to do it,
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.
DWR is Easy Ajax for Java
See the demo
DWR will generate the JavaScript to allow web browsers to securely call into Java code almost as if it was running locally. It can marshal virtually any data including collections, POJOs, XML and binary data like images and PDF files. All that is required is a security policy that defines what is allowed.
With Reverse Ajax, DWR allows Java code running on a server to use client side APIs to publish updates to arbitrary groups of browsers. This allows interaction 2 ways - browser calling server and server calling browser. DWR supports Comet, Polling and Piggyback (sending data in with normal requests) as ways to publish to browsers.
DWR provides integration with Dojo, TIBCO GI, Scriptaculous in the browser, and with Spring, Struts, Guice, Hibernate and others on the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With