Can someone give me an example of how to make an ajax call by JQuery within an HTML page to a Java Servlet (please post the full code of the html page, the call and the Servlet Class). I want to do this in an Dynamic Web Project in Eclipse. I guess the web.xml must be modified too in order to do this so please explain how to modify this file, too. Are there any other files that must be modified ?
Regards and thanks in advance, Michael
First I create the Servlet, it don't have any additional code to handle an Ajax request, so in my example I get two parameters from the request added them and return an String with the result, very simple.
I'm using the 3.0 version of the Servlet container so I can specify the information of the Servlet Url Mapping with the annotation @WebServlet and I don't need to modify my web.xml.
The Html is very simple it has two inputs to get the operands and it has 3 buttons, The first one call the servlet without Ajax, the second call the servlet with ajax getting the parameters of the form and the last call with ajax but it send the parameters using json.
*Observations: * I use the method get because I want to show the answer with a no ajax call, you should use POST. I test this example with Tomcat 7.0. If you need to receive data to be serialized to objects (You need to receive an object) or to return and object you need to use for the communication JSON and in the servlet use some JSON Serializer I recommend you GSON o Jackson, so you receive a JSON String as parameter and deserialize in the servlet, to respond serialize your Object to JSON and send in the response, if you send JSON you need to change the data attribute of the jquery ajax call so data: "json"