Explain getParameterNames() method with example.
Reading Form Parameters
Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using has MoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
Example
//ReadParams.html file
<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked"/> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
//ReadParams.java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ReadParams extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Printwriter out = response.getWriter();
Enumeration paramNames = request.getParameterNames();
out.println("<html><head><title>Reading All Parameters </title>
</head><body bgcolor=\"#f0f0f0\"><table width=\"50%\"
border=\"1\"align="center\"><tr><th>Param Name</th>
<th>Param Values</th></tr>");
while(paramNames.hasMoreElements())
{
String paramName = (string)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues=request.getParameterValues (paramName);
if (paramValues.length == 1)
{
String paramValue = paramValues[0];
if (paramValue. length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
}
else
{
out.println("<ul>");
for(int i=0; i <paramValues.length; i++)
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
out.println("</tr></table></body></html>");
}
}
Comments
Post a Comment