Simple calculator with JSP/Servlet and Ajax Simple calculator with JSP/Servlet and Ajax ajax ajax

Simple calculator with JSP/Servlet and Ajax


it seems too big for my scale

That really depends on the context and the functional requirements. It's pretty simple and trivial though. It more sounds like that it's "too much info" for you and that you actually need to learn the separate concepts (HTTP, HTML, CSS, JS, Java, JSP, Servlet, Ajax, JSON, etc) individually so that the bigger picture (the sum of all those languages/techniques) becomes more obvious. You may find this answer useful then.

Anyway, here's how you could do it with just JSP/Servlet without Ajax:

calculator.jsp:

<form id="calculator" action="calculator" method="post">    <p>        <input name="left">        <input name="right">        <input type="submit" value="add">    </p>    <p>Result: <span id="result">${sum}</span></p></form>

with CalculatorServlet which is mapped on an url-pattern of /calculator:

@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    Integer left = Integer.valueOf(request.getParameter("left"));    Integer right = Integer.valueOf(request.getParameter("right"));    Integer sum = left + right;    request.setAttribute("sum", sum); // It'll be available as ${sum}.    request.getRequestDispatcher("calculator.jsp").forward(request, response); // Redisplay JSP.}

Making Ajaxical stuff to work is also not that hard. It's a matter of including the following JS inside the JSP's HTML <head> (please scroll to the right to see code comments which explains what every single line does):

<script src="http://code.jquery.com/jquery-latest.min.js"></script><script>    $(document).ready(function() {                                                   // When the HTML DOM is ready loading, then execute the following function...        $('#calculator').submit(function() {                                         // Locate HTML element with ID "calculator" and execute the following function on its "submit" event...            $form = $(this);                                                         // Wrap the form in a jQuery object first (so that special functions are available).            $.post($form.attr('action'), $form.serialize(), function(responseText) { // Execute Ajax POST request on URL as set in <form action> with all input values of the form as parameters and execute the following function with Ajax response text...                $('#result').text(responseText);                                     // Locate HTML element with ID "result" and set its text content with responseText.            });            return false;                                                            // Prevent execution of the synchronous (default) submit action of the form.        });    });</script>

and changing the last two lines of doPost as follows:

    response.setContentType("text/plain");    response.setCharacterEncoding("UTF-8");    response.getWriter().write(String.valueOf(sum));

You can even make it a conditional check so that your form still works for the case that user has JS disabled:

    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {        // Ajax request.        response.setContentType("text/plain");        response.setCharacterEncoding("UTF-8");        response.getWriter().write(String.valueOf(sum));    } else {        // Normal request.        request.setAttribute("sum", sum);        request.getRequestDispatcher("calculator.jsp").forward(request, response);    }


I'm not sure if this can help but it is atleast a simple calculator program

     protected void processRequest(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    /*READ THE FIRST NUMBER FROM TEXTBOX NAMED num1*/    Integer num1= Integer.parseInt(request.getParameter("num1"));     /*READ THE SECOND NUMBER FROM TEXTBOX NAMED num2*/    Integer num2=Integer.parseInt(request.getParameter("num2"));    /*READ THE OPERATOR VALUE FROM SELECT TAG NAMED operator*/    String operator=request.getParameter("operator");    /*THE FINAL RESULT*/    Integer result=0;    /*THE RESPONSE TO THE CLIENT WILL BE IN HTML FORMAT*/    response.setContentType("text/html");    PrintWriter out = response.getWriter();    try {        /*ALTERNATIVELY IF STATEMENT CAN ALSO BE USED                   if("+".equals(operator))      {          result = num1 + num2;      }      else if("-".equals(operator))      {          result = num1 - num2;      }      else if("*".equals(operator))      {          result = num1 * num2;      }      else if ("/".equals(operator))      {          result = num1 / num2;      }        */        switch(operator)        {            case("+"): /*IF PLUS*/                result=num1+num2;                break;            case("-"): /*IF MINUS*/                result=num1-num2;                break;            case("*"): /*IF MULTIPLICATION*/                result=num1*num2;                break;            case("/"): /*IF DIVISION*/                result=num1/num2;                break;        }        /* TODO output your page here. You may use following sample code. */        out.println("<!DOCTYPE html>");        out.println("<html>");        out.println("<head>");        out.println("<title>Servlet ServletCalculator</title>");                    out.println("</head>");        out.println("<body>");        /*THE PART OF OUTPUT TO THE CLIENT*/        out.println("<h1>" + num1 +" "+operator+" "+num2+" = " + result+"</h1>");        out.println("</body>");        out.println("</html>");    } finally {                    out.close();    }}

and the html is

    <!DOCTYPE html>    <html>        <body>            <form action="ServletCalculator">                enter first number <input name="num1" type="text"/>        <select name="operator">            <option value="+"> + </option>            <option value="-"> - </option>            <option value="*"> * </option>            <option value="/"> / </option>        </select>        enter second number <input name="num2" type="text"/>        <button type="submit"> Calculate </button>            </form>        </body>    </html>


probably, the simplest way will be create form with two fields and submit button. In server side you can add two numbers and print it.Smt like:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    response.setContentType("text/html");    int a = Integer.valueOf(request.getParameter("a"));    int b = Integer.valueOf(request.getParameter("b"));    int res = a + b;    response.getWriter().println(res);}