Saturday, May 4, 2013
Today I will tell you how you can get the parameter values submitted by a client to a server using servlets. Here you will see different process of extracting the form parameters depending on your requirements. Here we will use getParameter() , getParameterValues() , getParameterNames() and getParameterMap() methods.
 getParameter() : This method returns only a single value associated with the parameter name. This is generally used when you have only one value for a parameter.
getParameterValues() : It returns an array of all values associated with a parameter name. This is used when you have multiple values for a parameter.
getParameterNames() : It returns an Enumeration<String> which are the different parameter names. Now you can use individual name and extract the values. This is used when you dont know the param names. But in reality you will always know them from beforehand.
getParameterMap() : It returns a Map of parameter names mapped to all values associated with each parameter. This is the most general case.
Servlet Source Code
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

public class ParamReader extends HttpServlet{
   public void doGet(HttpServletRequest req,HttpServletResponse res){
        //used when one parameter has only one value
String fn=req.getParameter("fn");

//used when one parameter has more than one vakue
String str[]=req.getParameterValues("fn");  //getting all values

//used when parameter names are unknown
Enumeration<String> en=req.getParameterNames();  //getting all names
          req.getParameter(en.nextElement());  //getting vakue
      //used to get whole map
Map<String,String[]> m=req.getParameterMap();
Set<String> s=m.keySet();  //key set means param names
Iterator<String> it=s.iterator();
          m.get(;  //param values
Download Links
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared


Post a Comment

Total Pageviews

Subscribe via Email


Popular Posts