AJP Lab Exercise-10


 10. Write down the program in which input the two numbers in          an html file and then display the addition in JSP file.

------------------------------------------


input.html


<!DOCTYPE html>
<html>
<head>
    <title>Addition Form</title>
</head>
<body>
    <h2>Enter Two Numbers</h2>
    <form action="add.jsp" method="post">
        Number 1: <input type="text" name="num1"><br><br>
        Number 2: <input type="text" name="num2"><br><br>
        <input type="submit" value="Add Numbers">
    </form>
</body>
</html>



-----------------------------------------------------

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Addition Result</title>
</head>
<body>
    <h2>Result of Addition</h2>
    <%
        // Fetch values from request
        String s1 = request.getParameter("num1");
        String s2 = request.getParameter("num2");

        int n1 = 0, n2 = 0, sum = 0;

        if(s1 != null && s2 != null && !s1.equals("") && !s2.equals("")) {
            try {
                n1 = Integer.parseInt(s1);
                n2 = Integer.parseInt(s2);
                sum = n1 + n2;
    %>
                <p><b><%= n1 %> + <%= n2 %> = <%= sum %></b></p>
    <%
            } catch(NumberFormatException e) {
    %>
                <p style="color:red;">Please enter valid integer numbers!</p>
    <%
            }
        } else {
    %>
            <p style="color:red;">Please enter both numbers!</p>
    <%
        }
    %>
</body>
</html>