reading unknown parameters in a servlet

In this post, you will learn:

  • How to read unknown parameters in a servlet?
  • In which case unknown parameters are used?

When unknown parameters are used in a servlet?

Sometimes input forms are not available to the servlet programmers i.e. the programmer doesn’t know how many parameters are submitted by the user as part of the request . In such a case, the servlet need to defined in such a way that all the parameter name of which are not known are read and processed.

How multi unknown parameters can be read in servlet?

Unknown parameters can be read in a servlet in two ways with the help of following methods.

1. getParameterMap(): This method of ServletRequest interface returns an immutable map of request parameters. It has following syntax:

public Map<String,String[]> getParameterMap();

2. getParameterNames(): This method of ServletRequest interface returns an Enumeration of all the request parameters names. Once parameters names are known their values are obtained using getParameterValues() method. It has following syntax:

public Enumeration<String> getParameterNames();

Use of getParameterMap() method requires more efforts than as is described by the following practical example.

Practical example of unknown parameters:

First, the index.html it has single valued as well as multi valued input controls. It has two submit buttons, which are used to get the request processed by NormalProcessing or EasyProcessing servlet.

<form method="post" action="processingServlet">
Title: <select name="title">
		<option  value="Mr.">Mr.</option>
		<option  value="Mrs.">Mrs.</option>
		<option  value="Miss">Miss</option>
	  </select><br/>
Name:   <input type="text" name="name"> <br/>

Gender: 
           <input type="radio" name="gender" value="Male">Male   
           <input type="radio" name="gender" value="Female">Female<br>
           
I use following options for investment: <br/>
           <input type="checkbox" name="investment_option" value="Bank FD & RD">Bank FD & RD<br/>
           <input type="checkbox" name="investment_option" value="Mutual Funds">Mutual Funds<br/>
           <input type="checkbox" name="investment_option" value="Shares">Shares<br/>
           
<input type="submit" name="btn" value="Process">
<input type="submit" name="btn" value="Process Easy">			   
</form>

Second the ProcessingServlet, It receives request from the index.html and forwards it to the NormalProcessing or EasyProcessing servlet on the basis of the value of submit button.

package com.techmentro.learningpad;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ProcessingServlet extends HttpServlet
{
	
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		
		//Values of the button is obtained.
		String btn=request.getParameter("btn");
		RequestDispatcher rd;
		//Using the button value, RequestDispatcher is created for normalProcessing or easyProcessing servlet.
		if(btn.equalsIgnoreCase("Process"))
		rd=request.getRequestDispatcher("/normalProcessing");
		else
		rd=request.getRequestDispatcher("/easyProcessing");
		//Request is forwarding to the toughProcessing or easyProcessing servlet.
		rd.forward(request,response);
	}
}

Third the NormalProcessing servlet, It uses getParameterMap() method of ServletRequest interface to read the unknown parameters. This approach is lengthy because first an entry set is obtained from the map. Second an iterator is obtained from the entry set. Third, in each iteration a Map.Entry object is obtained from the iterator. Fourth key & value objects are obtained from the Map.Entry object.

package com.techmentro.learningpad;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class NormalProcessing extends HttpServlet
{
	
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		
		PrintWriter out=response.getWriter();
		response.setContentType("text/html");
		
		//Parameter map is obtained.
		Map<String,String[]> params=request.getParameterMap();
		//EntrySet is obtained from the map so that its elements can be traversed.
		Set<Map.Entry<String,String[]>> set=params.entrySet();
		//Iterator is obtained from the set.
		Iterator<Map.Entry<String,String[]>> itr=set.iterator();
		//parameters names & values are obtained and sent back as response.
		while(itr.hasNext())
		{
		//Map.Entry object is obtained from the iterator	
		Map.Entry<String,String[]> entry=itr.next();
		//parameter name is obtained from the entry
		String pname=entry.getKey();
		//pname is written to the output stream
		out.println("<b>"+pname+"</b>:");
		//parameter values are obtained
		String pvalues[]=entry.getValue();
		for(String pvalue:pvalues)
			//parameter values are written to the output stream.
			out.println("<b>"+pvalue+"</b><br/>");
		}
		
		out.close();
	}
}

Fourth the EasyProcessing servlet, It uses getParameterNames() and getParameterValues() methods of ServletRequest interface to read the unknown parameters.

package com.techmentro.learningpad;

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

public class EasyProcessing extends HttpServlet
{
	
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		
		PrintWriter out=response.getWriter();
		response.setContentType("text/html");
		
		//Parameter names are obtained.
		Enumeration<String> pnames=request.getParameterNames();
		
		//parameters names & values are obtained and sent back as response.
		while(pnames.hasMoreElements())
		{
		//parameter name is obtained from the Enumeration	
		String pname=pnames.nextElement();
		//pname is written to the output stream
		out.println("<b>"+pname+"</b>:");
		//parameter values are obtained
		String pvalues[]=request.getParameterValues(pname);
		
			for(String pvalue:pvalues)
			//parameter values are written to the output stream.
			out.println("<b>"+pvalue+"</b><br/>");
		}
		out.close();
	}
}

Fifth, the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  
 <servlet>
    <servlet-name>s1</servlet-name>
    <servlet-class>com.techmentro.learningpad.ProcessingServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>s1</servlet-name>
    <url-pattern>/processingServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>s2</servlet-name>
    <servlet-class>com.techmentro.learningpad.NormalProcessing</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>s2</servlet-name>
    <url-pattern>/normalProcessing</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>s3</servlet-name>
    <servlet-class>com.techmentro.learningpad.EasyProcessing</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>s3</servlet-name>
    <url-pattern>/easyProcessing</url-pattern>
  </servlet-mapping>
  
</web-app>

Output screen images of the practical example:

This screen displays the input form generated by index.html. Note that it has two submit buttons.

unknown_parameters_screen1

The second screen represents the response generated by NormalProcessing servlet which is invoked when Process button is used to submit the request.

unknown_parameters_screen2

The third screen represents the response generated by EasyProcessing servlet which is invoked when Process Easy button is used to submit the request.

unknown_parameters_screen3

Its time to recap the main concepts:

  1. If input form is not available to the servlet programmer then the servlet need to be defined to read unknown parameters.
  2. unknown parameters can be read in a servlet in two ways.
  3. First, by using getParameterMap() method of the ServletRequest interface.
  4. Second, by using getParameterNames() and getParameterValues() methods of the ServletRequest interface.

Example Source Code

If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *