ServletRequest and ServletResponse -


javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest Interfaces -

Servlet container creates ServletRequest or HttpServletRequest objects that provides client browser request information to server. ServletRequest and HttpServletRequest contains several methods that we can use to get client data.

Fig:- HttpServletRequest inherit ServletRequest interface

HttpServletRequest interface defines methods that are specific to HTTP protocol, that servlet can use to interact with client browser.

ServletRequest Methods -

Some important methods of ServletRequest are as follows -
Method name with return type Description
1- String getParameter(String paramName) - Whenever client makes a request to server, request may contain some extra information in the form of Request Parameters, we can access these parameter values in servlets using getParameter() method. We can use this method if parameter has only single value (for example - textbox).
It return the value of parameter as String, whose name is specified by paramName.
2- String[] getParameterValues(String paramName) If request parameter has more than one value (for example - Drop down list) then we can use getParameterValues() method to access those values. It returns values of Parameter in the form of String array.
It reurns values of Parameter specified by paramName in the form of String array.
3- java.util.Enumeration<String> getParameterNames() This method is used to get names of parameters in client request.
It returns all parameter names in client request in the form of Enumeration of String type.
4- Object getAttribute(String attributeName) This method is used to get the value of attribute from request object.
It returns the value of attribute as Object, whose name is specified by attributeName.
5- java.util.Enumeration<Strng> getAttributeNames() This method is used to get all the attributes name from request object.
It returns the name of all attributes in the form of Enumeration of String type.
6- String getContentType() This method is used to get the type of content (for example - text/html, text/plain etc.)in request body.
7- int getContentLength() This method is used to get the length of content in request body in bytes.

Example -

This example will show you the working and use of different methods of ServletRequest -
1- index.html or index.jsp - This will be your default page.
<body>
<form method="post" action="MyServlet1">
Enter your name: <input type="text" name="name" placeholder="your name"><br><br>
Enter your hobbies: 
<select name="hobbies" multiple size="3">
<option>Playing Cricket</option>
<option>Playing Football</option>
<option>Playing Hockey</option>
<option>Traveling</option>
<option>Singing</option>
</select><br>

<input type="submit" value="Submit">
<input type="reset" value="Reset"> 
</form>
</body>     

The index.html page contains a Textbox and Multi Select list, When yow will enter submit button, it will redirect you to MyServlet1 URL.
2- MyServlet1 - Create a Package named "servs" and within "servs", create a Servlet named "MyServlet1"
 package servs;

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


public class MyServlet1 extends HttpServlet 
{
	
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
   try
     {
	PrintWriter out = response.getWriter();
        
        // Accessing Textbox value from request.
	String nm = request.getParameter("name");
   
        // Accessing selected list values from request.
	String[] hb = request.getParameterValues("hobbies");  

        // Accessing names of all parameters available in request.
	java.util.Enumeration<String> paramNames = request.getParameterNames(); 

        //Accessing MIME type of request body.
	String cntype = request.getContentType();
	
       //Accessing size of content in request body.
        int size = request.getContentLength();
			
	out.println("Employee :- "+nm+ "has the following hobbies:-");
	for(String h:hb)
	{
	 out.println(h);
	}
	
	out.println("Parameter Name are - ");
	while(paramNames.hasMoreElements())
	 {
	  String pn = paramNames.nextElement();
	  out.println(pn);
	 }
			
	out.println("Content type is:- "+cntype);
			
	out.println("Content Size is:- "+size+" bytes");
     }
   catch (Exception ex) 
    {
     System.out.println(ex);	
    }
 }
}   
 
3- web.xml - Add the following code to web.xml within web-app
<servlet>
  <servlet-name>demo</servlet-name>
  <servlet-class>servs.MyServlet1</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/MyServlet1</url-pattern>
  </servlet-mapping>
     
 


3.1 - Use of Annotation in place of web.xml for Servlet Mapping -

Java defines a package named "javax.servlet.annotation" that provides us various annotations we can use to declare servlet, listeners, filters etc.
For servlet mapping, it defines a annotation named "javax.servlet.annotation.WebServlet". We can use it to define url pattern of our servlet. This annotation gets processed by web container at the deployment time of our servlet.
To use annotation make the following changes to "MyServlet1" servlet -
package servs;

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


@WebServlet("/MyServlet1")   // /MyServlet1 will be url pattern of this servlet
public class MyServlet1 extends HttpServlet
{
	
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 {
		
  try
  {
        PrintWriter out = response.getWriter();
        
        // Accessing Textbox value from request.
	String nm = request.getParameter("name");
   
        // Accessing selected list values from request.
	String[] hb = request.getParameterValues("hobbies");  

        // Accessing names of all parameters availabel in request.
	java.util.Enumeration<String> paramNames = request.getParameterNames(); 

        //Accessing MIME type of request body.
	String cntype = request.getContentType();
	
       //Accessing size of content in request body.
        int size = request.getContentLength();
			
	out.println("Employee :- "+nm+ "has the following hobbies:-");
	for(String h:hb)
	{
	 out.println(h);
	}
	
	out.println("Parameter Name are - ");
	while(paramNames.hasMoreElements())
	 {
	  String pn = paramNames.nextElement();
	  out.println(pn);
	 }
			
	out.println("Content type is:- "+cntype);
			
	out.println("Content Size is:- "+size+" bytes");
     }
   catch (Exception ex) 
    {
     System.out.println(ex);	
    }
 }
}   
Now we do not need to add servlet information in web.xml file.
4- Now run your project, and it will show you index.html page, enter your choices.



Now enter the submit button and it will show you the following output -



Download this project in Eclipse IDE
Download this project in NetBeans IDE

HttpServletRequest methods -

Some important methods of HttpServletRequest are as follows -
Method name with return type Description
1- HttpSession getSession() - It returns current session from client request or create and returns a new session object if it does not exist previously.
2- Cookie[] getCookies() This method returns all the cookies from client request object in the form of Cookie array.If no cookie availabel in client request than it returns null.
3- String getHeader(String headerName) This method returns the header value from client request corresponding to header name specified by headerName.If there is no header available in request corresponding to specified header name, then it will return null.
4- String getQueryString() This method returns query string available in client request url.(for example if client request url is - "www.gettechnotes.com?t1=admin&t2=123", in this case "t1=admin&t2=123" will be query string.).
These methods will be used ahead.

javax.servlet.ServletResponse and javax.servlet.http.HttpServletResponse interface -

ServletResponse or HttpServletResponse objects are used to send servlet response back to client. They provides several methods that we can use to send response.

Fig: ServletResponse interface inherit HttpServletResponse interface


ServletResponse methods -

Some imporatent methods of ServletResponse are as follows -
Method name with return type Description
1- PrintWriter getWriter() throws IOException - It returns java.io.PrintWriter object, that can be used to send text characters in response. It has methods print() and peintln(), that we can use to write text.
2- void setContentType(String type) This method is used to set the type of content (for example - "text/html" or "text/plain" etc.) sent in response from server. It inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
3- void setContentLength(int length) This method is used to set the length of content in response body.
4- ServletOutputStream getOutputStream()throws IOException This method returns a ServletOutputStream object, that we can use to send binary data in response.

HttpServletResponse methods -

Some important methods of HttpServletResponse are as follows -
Method name with return type Description
1- void addCookie(Cookie cookieObj) This method is used to add cookie specified by cookieObj in response.
2- void addHeader(String name, String value) This method is used to add a header with specified name and value.
3- String encodeURL(String urlToEncode) This method is used for URL rewriting. i.e. if client turned off cookies of browser, then we can use this method fro session tracking.
It adds the session id in URL specified by urlToEncode, and if encoding is not required, it returns the same unchanged url.
4- void sendRedirect(String loc)throws IOException This method is used to redirect from one page to another.Details of sendRedirect() will be covered next.
5- String encodeRedirectURL(String urlToEncode) This method is similar to encodeURL(), i.e. used for URL rewriting.
If we want URL rewriting in case of sendRedirect() method, then we use encodeRedirectURL() method instead of sendRedirect().
6- sendError(int statusCode, String errorMsg)throws IOException This method is used to send an error message with status code in response to client.