JQuery, Java Servlet Examplet within Eclipse WTP

3.4k views Asked by At

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

1

There are 1 answers

5
Cesar Loachamin On BEST ANSWER

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.

@WebServlet("/CalculatorServlet")
public class CalculatorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get the parameters from the request
        String param1 = request.getParameter("param1");
        String param2 = request.getParameter("param2");

        int result = Integer.parseInt(param1) + Integer.parseInt(param2);
        String responseResult = "The result is " + result;

        response.setContentType("text/plain");
        response.getOutputStream().write(responseResult.getBytes());
    }

}

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.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>

    <fieldset>
        <legend>Parameters</legend>
        <form id="form1" action="CalculatorServlet" method="get">
            <label for="param1" > Operand 1</label>
            <input type="number" id="param1" name="param1">
            <label for="" id="param2">Operand 2</label>
            <input type="number" id="param2" name="param2">
            <div>
            <input type="submit" value="Submit without Ajax">
            <input type="button" value="Submit with Ajax" id="btnCall1">
            <input type="button" value="Submit param1 and 2" id="btnCall2">
            </div>
        </form>
    </fieldset>

    <script>
        (function() {
            $("#btnCall1").click(function() {
                $.ajax({
                    url : "CalculatorServlet",
                    type: "get",
                    data: $("#form1").serialize(),                  
                    dataType: "text",                   
                    success: success,
                    error: error
                });
            });

            $("#btnCall2").click(function() {
                var param1Value = $("#param1").val();
                $.ajax({
                    url : "CalculatorServlet",
                    type: "get",
                    data: {param1: param1Value, param2: 2},                 
                    dataType: "text",                   
                    success: success,
                    error: error
                });
            });

            function success(data, textStatus, jqXHR)
            {
                alert(data);
            }

            function error(jqXHR, textStatus, errorThrown)
            {
                alert("error "+textStatus);
            }
        })();
    </script>
</body>
</html>

*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"