An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
public String[] getParameterValues(String name) returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box.
java.util.Enumeration getParameterNames() returns an enumeration of all of the request parameter names.
public int getContentLength() Returns the size of the request entity data, or -1 if not known.
public String getCharacterEncoding() Returns the character set encoding for the input of this request.
public String getContentType() Returns the Internet Media Type of the request entity data, or null if not known.
public ServletInputStream getInputStream() throws IOException Returns an input stream for reading binary data in the request body.
public abstract String getServerName() Returns the host name of the server that received the request.
public int getServerPort() Returns the port number on which this request was received.

Example of ServletRequest to display the name of the user

In this example, we are displaying the name of the user in the servlet. For this purpose, we have used the getParameter method that returns the value for the given request parameter name.


Enter your name

import javax.servlet.http.*;  
import javax.servlet.*;  
public class DemoServ extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
PrintWriter pw=res.getWriter();  
String name=req.getParameter("name");//will return value  
pw.println("Welcome "+name);