Write a program to receive two numbers from a HTML form and display their sum in the browser by using HttpServlet.
Aim: Write a program to receive two numbers from a HTML form and display their sum in the browser by using HttpServlet.
Program:
sum.html
<html>
<body>
<center>
<form name="Form1" method="post"
action="Add">
<table>
<tr>
<td><B>Enter First Number</td>
<td><input type=textbox name="First Number" size="25" value=""></td>
</tr>
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Second Number" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
Add.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add
extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Get print writer.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close();
}
}
web.xml( add following tags in web.xml)
<servlet>
<servlet-name>Add</servlet-name>
<servlet-class>Add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Add</servlet-name>
<url-pattern>/Add</url-pattern>
</servlet-mapping>
Output:
1. create .class file by compilining java file
2. places .class file in webapps -> servlets(folder created by program developer) -> WEB-INF -> classes
3. Add <servlet> and <servlet-mapping> tags in web.xml
4. run tomcat7( from bin folder)
5. type URL http://localhost:8080/servlets/sum.html
Labels: Advanced Java Lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home