Servlet Menu


Reading Form Parameters in Servlet




Servlets parse the form(client) data automatically using the following methods depending on the situation −
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the current request

Client pass some information from browser to web server uses GET Method or POST Method.

If a client send the data to the servlet, that data will be available in the object of HttpServletRequest interface. In case of getParameter() method we have to pass input parameter name and it will give the value.

request.getParameter("name")

If you are not aware of input parameter name? or if you have more input values its really tedious to use getParameter() method so we use getParameterNames(). 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 standard way by, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.

Enumeration en=request.getParameterNames();
while(en.hasMoreElements())
{
	String param_name = (String) en.nextElement();
	String value=request.getParameter(param_name);
	.......
}

login.html
<html lang="en">
 <head>
  <title>Login page</title>
 </head>
 <body>
 <h1> Login Form </h1> 
 <form method="post" action="login">
	Username: <input type="text" name="username">
	Password: <input type="password" name="pass">
 </form>
 </body>
</html>

LoginDemo.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class LoginDemo extends HttpServlet {

   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set response content type
      response.setContentType("text/html");

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      String name=request.getParameter("username");   //will return value  
	  out.println("Welcome "+name); 
	  out.close()
   }
}

web.xml
<web-app>
	<servlet>
		<servlet-name>login</servlet-name>
		<servlet-class>LoginDemo</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>login</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
</web-app>


Next Topic :Reading Initialization Paraeters

Suggestion/Feedback Form :




Excellent  Very Good  Good  Average  Poor


This is a Compliment
This is a Suggestion for improvement
This is Feedback
This is Grievance