17

This is sort of a continuation of my previous question, but I feel it deserved to be on its own, especially because of the very detailed answer I got.

I would like to create a simple calculator in JSP. There will be two textboxes for numbers and an add button. Ideally, I want the answer to appear in the page without reloading, but from the answer I got, it seems too big for my scale. I can think of either: 1) print the answer to a third textbox (is this possible?) or somehow loading the same page (with the add button and all) with the answer (and be able to enter different numbers and so on).

What is a good way to do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • You can create it without any servlets. Only with html + javascript. Another way - make calculations on server. Here you need Ajax to avoid page reloading. With way do you prefer and where you have problems? – Stan Kurilin Nov 06 '10 at 21:11

4 Answers4

23

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:

@Override
protected 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);
    }
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • a follow up for the first snippets: If I add another button that does a subtraction, how can I tell the servlet which one was pushed? – Amir Rachum Nov 06 '10 at 23:01
  • 1
    Button's name and value get sent as request parameter as well. Just check for its presence and/or its value. See also [this answer](http://stackoverflow.com/questions/954327/hidden-features-of-html/1978039#1978039). – BalusC Nov 06 '10 at 23:07
  • @BalusC: How to pass the button's value with the JS example (JQuery doesn't do it for "submit" input elements)? – AndrewBourgeois Jun 03 '12 at 01:25
  • @BalusC: I found out how: (1) prevent the form submission "$('#calculator').submit(function() { return false;});" (2) listen for clicks on the "submit types": "$('#calculator :submit').click(function(event){$form = $(this).parent("form"); $.post($form.attr('action'), $form.serialize()+ "&" + $(this).attr("name") + "=" + $(this).val(), function(responseText) { $('#result').text(responseText);});});" (this includes adding something after "serialize()". – AndrewBourgeois Jun 03 '12 at 02:38
  • 1
    @AndrewBourgeois: You're right, jQuery doesn't send the pressed button along. I've always used the [jQuery Form plugin](http://jquery.malsup.com/form/) to ajaxify forms and it was apparently the one which did that. I've incorrectly always assumed that it was ultimately done by jQuery itself with the `serialize()` function. Thank you for the wake up. – BalusC Jun 03 '12 at 03:52
  • @BalusC: In your program, jsp page adding two numbers and display the o/p it's fine.. but i have one problem i.e what are the result is coming after adding(on the previous result fresh result is overwriting), i want that result to be stay there only instead of overwriting can you help me on this. – Raki Feb 15 '13 at 10:31
3

I'm not sure if this can help, but it is at least 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 AN 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 the first number <input name="num1" type="text"/>
            <select name="operator">
                <option value="+"> + </option>
                <option value="-"> - </option>
                <option value="*"> * </option>
                <option value="/"> / </option>
            </select>
            Enter the second number <input name="num2" type="text"/>
            <button type="submit"> Calculate </button>
        </form>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
2

Probably, the simplest way will be create a form with two fields and a submit button. On the server side you can add two numbers and print it.

Something 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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
1

This can absolutely be done and can be done using simple HTML and JavaScript. You can avoid using server side Java calculation for this.

In my opinion, we should try to maintain the least load on the server. Don't load the server when this can be done at the client side.

Simple calculations, like addition, subtraction, multiplication and division, can be attained by writing JavaScript functions like add(a, b), sub(a, b), mul(a, b), div(a, b). And these functions can be called on different button click events.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bikash Rath
  • 159
  • 1
  • 7
  • As you might imagine, I asked this question (a long time ago) not because I wanted to create a startup based on online calculators, but because I wanted to learn JSP. – Amir Rachum Feb 16 '13 at 11:14
  • Ok. Got it. :). Just tried to help. In my defense I just started using stackoverflow to write answers. Previously for me it was just read only. :). So didn't notice that this question was asked long time ago. – Bikash Rath Feb 24 '13 at 06:20