Wednesday, July 27, 2016

Reading Servlet Parameters

Reading Servlet Parameters :

The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. 
The example contains two files. 
A Web page is defined in sum.html and a servlet is defined in Add.java

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="Enter First Number" size="25" value=""></td>
</tr>
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>


The HTML source code for sum.html defines a table that contains two labels and two text fields. One of the labels is Enter First Number,and the other is Enter Second Number. There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request.

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();
}
}

The source code for Add.java contains  doPost( ) method is overridden to process client requests. The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a loop.we can see that the parameter name and value are output to the client. The parameter value is obtained via the getParameter( ) method.

after typing URL : http://localhost:9999/servlets/sum.html





Labels:

1 Comments:

At April 15, 2020 at 8:21 AM , Blogger Unknown said...

Hi madam

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home