BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

ServletRequest Interface with example

By Chaitanya Singh | Filed Under: Java Servlet tutorial

❮ PreviousNext ❯

When a client sends a request to the web server, the servlet container creates ServletRequest & ServletResponse objects and passes them as an argument to the servlet’s service() method. The request object provides the access to the request information such as header and body information of request data.

First we will see an example and then we will see the list of methods available in the ServletRequest interface:

Example 1: ServletRequest getParameter() method to display the user input

In this example I am demonstrating the use of getParameter() method that returns the value of the given parameter.

In this html form, we are taking user input (name and age) and storing them in the parameters uname and uage respectively.
index.html

<form action="details" method="get">
 User Name: <input type="text" name="uname"><br>
 User Age: <input type="text" name="uage"><br>
 <input type="submit" value="submit">
</form>

MyServletDemo.java
In this servlet class we are getting the value of the parameters by using getParameter() method, this method belongs to the ServletRequest interface. In this example we have HttpServletRequest as a parameter of doGet() method, HttpServletRequest extends ServletRequest interface thats why the getParameter() method is available to the req object.

After getting the values, we are writing them on the webpage.

import javax.servlet.http.*; 
import javax.servlet.*; 
import java.io.*; 
public class MyServletDemo extends HttpServlet{ 
   public void doGet(HttpServletRequest req,HttpServletResponse res) 
   throws ServletException,IOException 
   {  
     res.setContentType("text/html"); 
     PrintWriter pwriter=res.getWriter(); 

     String name = req.getParameter("uname");
     String age = req.getParameter("uage");
     pwriter.println("Name: "+name); 
     pwriter.println("Age: "+age); 
     pwriter.close(); 
  }
}

Web.xml
This is your deployment descriptor file that maps the servlet to the url. Since our form has details page as action, we mapped the servlet class to the details page.

<web-app>
<display-name>BeginnersBookDemo</display-name>
   <welcome-file-list>
   <welcome-file>index.html</welcome-file>
   <welcome-file>index.htm</welcome-file>
   <welcome-file>index.jsp</welcome-file>
   <welcome-file>default.html</welcome-file>
   <welcome-file>default.htm</welcome-file>
   <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
<servlet>
   <servlet-name>BeginnersBook</servlet-name>
   <servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>BeginnersBook</servlet-name>
   <url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>

Output:
Screen 1:
ServletReqeust Output 1
Screen 2 that appears upon clicking submit:
ServletReqeust_Output_2

Example 2: Getting parameter names and values

In this example, we will be using getParameterNames() and getParameter() methods to get parameter names and values.
getParameterNames(): Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.

getParameter(): As mentioned above, this returns the value of given parameter.
index.html

<form action="details" method="get">
 User Name: <input type="text" name="uname"><br>
 User Age: <input type="text" name="uage"><br>
 <input type="submit" value="submit">
</form>

MyServletDemo.class

import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServletDemo extends HttpServlet{    
   public void doGet(HttpServletRequest req,HttpServletResponse res)    
      throws ServletException,IOException    
   {     
      PrintWriter pwriter=res.getWriter(); res.setContentType("text/html");
      Enumeration en=req.getParameterNames();
      while(en.hasMoreElements()) 
      { 
          Object obj=en.nextElement(); 
          String param=(String)obj; 
          String pvalue=req.getParameter(param); 
          pwriter.print("Parameter Name: "+param+  
             " Parameter Value: "+pvalue); 
      } 
      pwriter.close();   
      
    }
}

web.xml

<web-app>
<servlet>
 <servlet-name>BeginnersBook</servlet-name>
 <servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>BeginnersBook</servlet-name>
 <url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>

Output:

Example 3: Display Header information

index.html

<h1>Servlet Request Demo</h1>
<body>
<a href="headinfo">Click Here</a>
</body>

HeaderDetails.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HeaderDetails extends HttpServlet {

  public void doGet(HttpServletRequest request,
     HttpServletResponse response)
        throws IOException, ServletException 
  {
     response.setContentType("text/html");
     PrintWriter pwriter = response.getWriter();

     pwriter.println("HTTP header Information:<br>");

     Enumeration en = request.getHeaderNames();
     while (en.hasMoreElements()) {
        String hName = (String) en.nextElement();
        String hValue = request.getHeader(hName);
        pwriter.println("<b>"+hName+": </b>"
             +hValue + "<br>");
     }
  }
}

web.xml

<web-app>
<welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 
 <servlet>
 <servlet-name>BeginnersBook</servlet-name>
 <servlet-class>HeaderDetails</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>BeginnersBook</servlet-name>
 <url-pattern>/headinfo</url-pattern>
</servlet-mapping>
</web-app>

Output:

Methods of ServletRequest interface

String getParameter(String name): It returns the value of the given parameter as String or null if the given parameter does not exist.

Enumeration getParameterNames(): It returns an Enumeration of Strings objects containing the names of parameters in the request.

String[] getParameterValues(String name): It returns an array of Strings containing the all the values, the parameters has, returns null if parameter doesn’t have any value.

String getCharacterEncoding(): Returns the name of the character encoding used in the body of this request. This method returns null if the request does not specify a character encoding.

void setCharacterEncoding(String env): Overrides the character encoding in the body of the request.

int getContentLength(): Returns the length of the request content in bytes.

String getContentType(): Returns the MIME type of the body of the request, or null if the type is not known.

Note: I have just mentioned few of the methods. If you want a complete list of methods, then refer this official documentation.

❮ PreviousNext ❯

Leave a Reply Cancel reply

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

Servlet Tutorial

  • Servlet Introduction
  • Servlet API
  • Servlet Interface
  • Generic Servlet
  • HttpServlet
  • Servlet in Eclipse
  • Servlet Life cycle
  • Working of Servlet
  • Welcome-file-list
  • load-on-startup tag
  • ServletRequest
  • RequestDispatcher
  • ServletConfig
  • ServletContext
  • ServletResponse
  • HttpSession
  • Cookies
  • Servlet Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap