Share this page 

Detect no argument condition in a ServletTag(s): Servlet/JSP


Servlet 2.3
int i = req.getParameterMap().size();
if (i = 0) {
   // no arguments
   }
else  {
    Enumeration paramNames = req.getParameterNames();
    while(paramNames.hasMoreElements()) {
      String parm = (String)paramNames.nextElement();
      // do something with this parm
      }
    }
Previous version of the Servlet API
protected void doGet
    (HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException    {
  PrintWriter out = response.getWriter();
  response.setContentType( "text/html" ); 
  out.println("<HTML>"); 
  if (!request.getParameterNames().hasMoreElements()) {
     // no arguments
     out.println("<HEAD><TITLE>MyServlet (no args)</TITLE></HEAD>"); 
     out.println("<BODY>"); 
     out.println("<H1>MyServlet</H1>"); 
     out.println("<FORM METHOD='GET' ACTION='Servlet1'>"); 
     out.println("   Subject<INPUT TYPE=INPUT NAME=subject>"); 
     out.println("   Recipients<INPUT TYPE=INPUT NAME=to>"); 
     out.println("   Message<INPUT TYPE=INPUT NAME=message>"); 
     out.println("   <INPUT TYPE=SUBMIT VALUE='Ok'>"); 
     out.println(" </FORM>"); 
     }
  else  {
     out.println("<HEAD><TITLE>MyServlet (with args)</TITLE></HEAD>"); 
     out.println("<BODY>"); 
     out.println("<H1>Servlet</H1>"); 
     java.util.Enumeration paramNames = request.getParameterNames();
     while(paramNames.hasMoreElements()) {
       String parm = (String)paramNames.nextElement();
       out.println(parm + " = " + request.getParameter(parm) + "<BR>"); 
      }
  out.println("</BODY></HTML>"); 
  }
}