Expression tag for mathematical operation - JSP

Q. Write a JSP application to demonstrate the expression tag by using mathematical operation.

Answer:

There are multiple checkbox in html page to perform different mathematical operations. By default, Addition is checked and its add the given number in text box. At the time of division operation when we enter any invalid data in text box, it generates error message from "error.jsp" page.

input.html

<html>
    <title>Sample Example </title>
    <body>
        <form method="post" action="index.jsp">
            <fieldset style="width:30%; background-color:#b3d1ff">
                <h2><center> Mathematical Operation</center></h2>
                <hr>
                <font size=5 face="Times New Roman">
                    <input type="radio" name="a1" value="add" checked>Addition</input><br>
                    <input type="radio" name="a1" value="sub">Subtraction</input><br>
                    <input type="radio" name="a1" value="mul" >Multiplication</input><br>
                    <input type="radio" name="a1" value="div" >Division</input><br>
                </font>
                <table>
                <tr>
                    <td>Enter first Value:</td>
                    <td> <input type="text" name="t1" value=""></td>
                </tr>
                <tr>
                    <td>Enter second Value: </td>
                    <td><input type="text" name="t2" value=""></td>
                </tr><br>
                <tr>
                    <td></td>
                    <td><input type="submit" name="result" value="Check result!"></td>
                </tr>
                </table>
            </fieldset>
        </form>
    </body>
</html>


index.jsp

<%@ page errorPage="error.jsp" %>
<html>
    <body>
        <H1><center>Result for <%=request.getParameter("a1")%></center></H1>
        <%
            String num1=request.getParameter("t1");  
            String num2=request.getParameter("t2");  
  
            int i=Integer.parseInt(num1);  
            int j=Integer.parseInt(num2);  

            int k=0;
            String str=request.getParameter("a1");
            if(str.equals("add"))
                k=i+j;
            if(str.equals("sub"))
                k=i-j;
            if(str.equals("mul"))
                k=i*j;
            if(str.equals("div"))
                k=i/j;
        %>
        Result is: <%=k%>
    </body>
</html>


error.jsp

<%@ page isErrorPage="true" %>  
  
<h3>Sorry an exception occured!</h3>  
  
Exception is: <%= exception %>


web.xml

<web-app>
    <servlet>
        <servlet-name>xyz</servlet-name>
        <jsp-file>/input.html</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>xyz</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>


Output:

mathmetical operation

Result is: 200