04 - Servlets Request Response Session

4.1 INTRODUCTION TO SERVLET REQUEST AND SERVLET RESPONSE

In earlier chapters we discussed about the Servlets API and in this chapter we will discuss important methods and the usage of Request, Response and Session Classes.

In some of the servlet API methods like doGet(), doPost() or service() you must have seen Request and Response arguments.

There are several methods available in  Servlet Request /Response and in Session but we will discuss the most commonly used and important ones here.

The important and most commonly used functionality of ServletRequest are –

  • get the parameter from the user (front end)
  • store and get the objects in request scope
  • read the headers
  • get session object

Similarly for ServletResonse is used to-

  • Write the response back to user
  • Set or update the header values
  • Redirect to another url.

Http Session is used to store the attributes which are required in entire user session.

Let’s discuss these classes in details

4.2 SERVLET REQUEST /  RESPONSE PACKAGES

Request and Response related classes are packaged in two packages . These packages are -

  1. javax.servlet – This package contains ServletRequest and ServletResponse interfaces (protocol less).
  2. javax.servlet.http- This package contains HttpServletRequest, HttpServletResponse and HttpSession classes As package name suggest , this package contains all classes and interfaces related to HTTP protocol.

4.3 ServletRequest METHODS

As mentioned ServletRequest is the interface and below are its most commonly used methods with usage and description.

  • String getParameter(String parameterName)- this method is used to get the value of request parameter by name. Request parameters are the parameters sent by the user either as a query parameter or in the html form. Remember its return type is String.

http://localhost:8080?param=hello then we can get the parameter in the servlet like request.getParameter(“param”) and this call will return  “hello”

    • · ​String[] getParameterValues(String parameterName)- this method is similar to getParameter()  with the difference is that it  returns an array of String  containing all of the values the given request parameter.

    You might be wondering how we can have a multiple parameters with same name- so think of the scenarios where the check box has been used (user can select multiple options) OR a multi select dropdown.

    • Object getAttribute(String attributeName) – this method is used to get the attribute stored in a request scope by attribute name. Remember the return type is Object.
    • void setAttribute(String attributeName, Object value)-  this method is used to store an attribute in request scope. This method takes two arguments- one is attribute name and another is value.
    • As getAttribute() returns Object which means setAttribute() takes Object as well.
    • ServletContext getServletContext() – this method can be used to get the servlet context. The ServletContext contains information about the web application and is available in all servlets.

    Note: Do not get confused between parameter and attribute.

    • Parameters are the ones submitted by user in the form of query param or form elements where as attributes are the one which can be stored in request to take it later.
    • Parameters  cannot be set programmatically where as we can set the attributes.
    • Parameters are of type String where as attributes are Objects.

    4.4 ServletResponse METHODS

    Below are the important and most commonly used methods

    • PrintWriter getWriter() returns a PrintWriter object that can send the character text to the client.
    • void setContentType(String type) sets the content type of the response being sent to the client before sending the respond.

    ServletRequest and ServletResponse are the argument of service() method of GenericServlet

    4.5 HttpServletRequest

    HttpServletRequest is the Http protocol based request and extends ServletRequest Interface

    As HttpServletRequest extends Servlet Request all of its methods (discussed above) will be available. In addition to that the commonly used additional methods are-

    • Cookies getCookies()- this methods returns an array containing all of the Cookie objects the client sent with this request.
    • String getQueryString() this methods returns the query string that is contained in the request URL.
    • String getMethod()- this methods returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Do you remember we discussed different Request types in earlier chapter?  Based on this method
    • HttpSession getSession() this methods returns the current HttpSession associated with this request

    There is an overloaded method also available which takes a Boolean argument. if value of that argument is passed as true then it will return a current session and if there is no current session returns a new session. In case value is being passed as false then it returns null if session does not exist.

    • String getHeader(String headerName) – this method is used to get the any of header value based on given header name.

                     

    4.6 HttpServletResponse

    HttpServletResponse is the Http protocol based request and extends ServletResponse Interface

    As HttpServletResponse extends Servlet Response all of its methods (discussed above) will be available. In addition to that the commonly used additional methods are-

    • void addCookie(Cookie cookie)- this methods  adds the cookie object to the response.
    • void sendRedirect(String url)  this method redirects the browser to a specified URL from your servlet. We will discuss more about this method in later chapters.

    4.7 HttpSession 

    The HttpSession object is representation of a user session. User Session starts when a user opens a browser and sends the first request to server. Session object is available in all the request (in entire user session) so attributes stored in Http session in will be available in any servlet or in a jsp. When session is created, server generates a unique ID and attach that ID with the session. Server sends back this Id to the client and there on , browser sends back this ID with every request of that user to server with which server identifies the user.

    How to get a Session Object –

    As mentioned above session object can be retrieved using HttpServletRequest (not ServletRequest) object like –

    1. HttpSession session = request.getSession()
    2. HttpSession session = request.getSession(Boolean)

    Destroy or Invalidate Session –

    This is used to kill user session and specifically used when user logs off. To invalidate the session use -

    session.invalidate();

    Other important methods

    • Object getAttribute(String attributeName) – this method is used to get the attribute stored in a session scope by attribute name. Remember the return type is Object.
    • void setAttribute(String attributeName, Object value)-  this method is used to store an attribute in session scope. This method takes two arguments- one is attribute name and another is value.
    • void removeAttribute(String attributeName)-  this method is used to remove the  attribute from session.

    Note –

    You might be thinking that storing attribute in session is more convenient as compared to request. But be sure while you store attribute in session because session variables are available everywhere which means it may gets updated or removed from other part of code which can create  undesired behaviour. With request, all stored variables automatically gets vanished after request is completed.

    If you are sure that session variable is no longer will be used , remove it.

    Browser session and server sessions are different. Browser session is client session which starts when you opens browser and destroy on closing of browser where as server session are maintained at server end.

    SERVLET REQUEST /  RESPONSE EXAMPLES

    1. How to get the query parameter “param” in servlet?

    String value = request.getParameter(“param”);

    1. How to store a attribute in request?

    request.setAttribute(“attributeName”,”atributeValue”);

    1. How to get the stored request variable in example #b ?

    Object value =request.getAttribute(“attributeName”);

    String attribValue=value.toString();

    Remember getAttribute() always returns Object.

    1. How to send HTML back to the browser?

    PrintWriter writer = response.getWriter();

    writer.write("<html><body>Hello World</body></html>");

    1. How to redirect user to “google.com”?

    response.sendRedirect("http://www.google.com");  

    1. How to store a attribute in session?

    HttpSession session = request.getSession();

    session.setAttribute(“attributeName”,”atributeValue”);

    1. How to get the stored request variable in example #f ?

    HttpSession session = request.getSession();

    Object value =session.getAttribute(“attributeName”);

    String attribValue=value.toString();

    1. Write a HelloWorldServlet with both approaches (extends Generic Servlet and Http Servlet) which prints Hello World Message on browser.
    1. With Generic Servlet
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.GenericServlet;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class HelloWorldServlet extends GenericServlet 
    {
        @Override
        public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException 
    {
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            String helloWorldMessage="<html><body><H1>Hello World Servlet</H1></body></html>";
            writer.println(helloWorldMessage);
        }
    }
    
    

    Explanation

    • this servlet is written with GenericServlet approach, this servlet extends GenericServlet and overrides service() method and it takes ServletRequest and ServletResponse.
    • to write a response on the browser, we need a PrintWriter object which we can get from response so once Print Writer object is obtained, simply write the message.
    • This example clearly shows that we can write Html code in Print writer object.
    1. With HttpServlet
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;   
    public class HelloWorldServlet extends HttpServlet  {           
        @Override 
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
    {                                                 
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();  
            String helloWorldMessage="<html><body><H1>Hello World Servlet</H1></body></html>";  
            writer.println(helloWorldMessage);                                
        }                                                                
    }
    
    

    Explanation

    • since this servlet is written with HttpServlet approach, this servlet extends HttpServlet and overrides doGet() method and it takes HttpServletRequest and HttpServletResponse.
    • to write a response on the browser, we need a PrintWriter object which we can get from response so once Print Writer object is obtained, simply write the message.

    Like us on Facebook