Add two numbers in JSP easily

Adding two numbers
Here is an example on adding up two numbers in JSP. This is very simple as you see below. This requires very small piece of code. All i have done here is created a HTML file containing the input fields which contain the numbers to add up.Now the values in the input field are of type String, so i have done type casting and converted them into int using Integer.parseInt(). See how easy it looks.



Folder structure

Project folder: D:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\inputjsp


inputjsp
           |_ index.html
           |_ add.jsp
           |_ WEB-INF
                              |_ web.xml

index.html


<html>

    <head>
        <title>Enter two numbers to add up</title>
    </head>
   
    <body>
        <form action="./add.jsp">
            First number: <input type="text" name="t1"/>
            Second number: <input type="text" name="t2"/>
            <input type="submit" value="SUBMIT" />
        </form>
    </body>

</html>


add.jsp


<html>
    <head>
        <title>Enter two numbers to add up</title>
    </head>
   
    <body>
    <%= "<h1> The sum is "+(Integer.parseInt(request.getParameter("t1"))+Integer.parseInt(request.getParameter("t2")))+"</h1>"%>
    </body>
</html>


web.xml


<web-app></web-app>

Sample Output


Enter the input for JSP file Sum of the two numbers printed

Explaining the code

The HTML file contains the most known code as seen in many servlet programs. The form action directs to the JSP file add.jsp to which the user request is sent. Simple is that. The <input type="text"> creates an input field (textfield) for typing text and the type submit creates a SUBMIT button capable of submitting the form when clicked on it.

t1 is the name of the input field taking the first number.
t2 is the name of the input field taking the second number.

The JSP file is easy. In the <%= and %> there is an expression which gets printed on the webpage. If you can observe the expression, you'll find that the as the value in the input field is of type String, it is typecasted into int with the use of Integer.parseInt(String num)

request.getParameter("t1"): This returns the value that the user typed in the text field t1 in the form of String. The same thing applies for the request.getParameter("t2") also but here we'll get the value the user typed in the 2nd field.

I wanted to make it appear big. So I enclosed the text in <h1> tag.

Nothing is written in web.xml but this needs to be declared or created because the Tomcat has to recognize this as a web application, I have started and closed <web-app> tag. This needs to be in WEB-INF as you have learned previously.

In this way, we can simply add up two numbers in JSP easily with two files.

Also see, Hello World Example in JSP with Explanation to get started with the basic JSP program.


Posted by at on

Tags: Java Server Pages,