0% found this document useful (0 votes)
127 views2 pages

Sum Servlet Program

The document outlines a Java Servlet program for calculating the sum of two numbers. It includes an HTML form for user input and a Java Servlet that processes the input, calculates the sum, and displays the result. Additionally, it provides an optional web.xml mapping for the servlet configuration.

Uploaded by

introvertb46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views2 pages

Sum Servlet Program

The document outlines a Java Servlet program for calculating the sum of two numbers. It includes an HTML form for user input and a Java Servlet that processes the input, calculates the sum, and displays the result. Additionally, it provides an optional web.xml mapping for the servlet configuration.

Uploaded by

introvertb46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Servlet Program: Sum of Two Numbers

1. HTML Page: [Link]


<!DOCTYPE html>
<html>
<head><title>Sum Calculator</title></head>
<body>
<center>
<h2>Enter Two Numbers to Calculate Sum</h2>
<form method="post" action="[Link]
<table>
<tr><td><b>Number 1:</b></td><td><input type="text" name="num1" size="25"
value=""></td></tr>
<tr><td><b>Number 2:</b></td><td><input type="text" name="num2" size="25"
value=""></td></tr>
</table>
<br><input type="submit" value="Calculate Sum">
</form>
</center>
</body>
</html>

2. Java Servlet: [Link]


import [Link].*;
import [Link].*;
import [Link].*;

public class SumServlet extends GenericServlet {


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter pw = [Link]();

String num1Str = [Link]("num1");


String num2Str = [Link]("num2");

[Link]("<html><body>");
[Link]("<h2>Sum Result:</h2>");

try {
int num1 = [Link](num1Str);
int num2 = [Link](num2Str);
int sum = num1 + num2;
[Link]("<p>The sum of " + num1 + " and " + num2 + " is: <b>" + sum + "</b></p>");
} catch (NumberFormatException e) {
[Link]("<p style='color:red;'>Please enter valid numeric values.</p>");
}

[Link]("</body></html>");
[Link]();
}
}

3. Optional: [Link] Mapping


<web-app>
<servlet>
<servlet-name>SumServlet</servlet-name>
<servlet-class>SumServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SumServlet</servlet-name>
<url-pattern>/SumServlet</url-pattern>
</servlet-mapping>
</web-app>

You might also like