Servlet attributes and their scope

Servlet attributes and their scope

Servlet attributes are objects associated with various scopes within a servlet-based web application. They can be used to pass information between different components such as servlets, JSPs, and filters. Attributes can be added, retrieved, and removed using specific methods provided by the servlet API.

Scopes of Servlet Attributes

There are three main scopes for servlet attributes:

1.  Request Scope

  • Description:  Attributes are bound to a single request. They are available from the moment a request is received until the response is sent back to the client.
  • Use Case:  Passing information between different components handling the same request.

  • Methods:  
  •  setAttribute(String name, Object value) – Sets an attribute.
  •  getAttribute(String name) – Retrieves an attribute.
  •  removeAttribute(String name) – Removes an attribute.
  •  Example:  request.setAttribute(“name”, “value”);

2.  Session Scope:

  • Description:  Attributes are bound to a specific user session. They remain available across multiple requests from the same user until the session is invalidated or expires.
  • Use Case:  Storing user-specific data such as login information.

  • Methods
  • setAttribute(String name, Object value) – Sets an attribute.
  • getAttribute(String name) – Retrieves an attribute.
  • removeAttribute(String name) – Removes an attribute.
  • Example:  session.setAttribute(“name”, “value”);

3.  Application Scope (ServletContext):

  • Description:  Attributes are bound to the entire web application. They are available to all components and all requests within the same application context.
  • Use Case:  Sharing global information such as application-wide settings or resources.

   Methods:  

  •  setAttribute(String name, Object value) – Sets an attribute.
  •  getAttribute(String name) – Retrieves an attribute.
  •  removeAttribute(String name) – Removes an attribute.
  •  Example:  getServletContext().setAttribute(“name”, “value”);

Let’s illustrate the use of servlet attributes in different scopes with examples.

Servlet attributes

Using Request Scope Attributes
1.  Servlet Setting Request Attributes: 

java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/requestAttribute")
public class RequestAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("message", "Hello from Request Scope");
        request.getRequestDispatcher("/displayRequestAttribute").forward(request, response);
    }
}

Servlet Retrieving Request Attributes:
2.  Servlet Retrieving Request Attributes: 
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/displayRequestAttribute")
public class DisplayRequestAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String message = (String) request.getAttribute("message");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h2>" + message + "</h2>");
        response.getWriter().println("</body></html>");
    }
}

Example: Using Session Scope Attributes
Example: Using Session Scope Attributes
1.  Servlet Setting Session Attributes: 

java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/sessionAttribute")
public class SessionAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("user", "John Doe");
        response.sendRedirect("displaySessionAttribute");
    }
}

Servlet Retrieving Session Attributes:
2.  Servlet Retrieving Session Attributes: 
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/displaySessionAttribute")
public class DisplaySessionAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h2>User: " + user + "</h2>");
        response.getWriter().println("</body></html>");
    }
}

Using Application Scope Attributes
1.  Servlet Setting Application Attributes: 

java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/applicationAttribute")
public class ApplicationAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getServletContext().setAttribute("appName", "My Web Application");
        response.sendRedirect("displayApplicationAttribute");
    }
}

Servlet Retrieving Application Attributes:
2.  Servlet Retrieving Application Attributes: 
java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/displayApplicationAttribute")
public class DisplayApplicationAttributeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String appName = (String) getServletContext().getAttribute("appName");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h2>Application Name: " + appName + "</h2>");
        response.getWriter().println("</body></html>");
    }
}

Explanation of the Examples

  • Request Scope Example:
  • The RequestAttributeServlet sets a request attribute named “message” and forwards the request to DisplayRequestAttributeServlet, which retrieves and displays the attribute.
  • Session Scope Example:
  • The SessionAttributeServlet sets a session attribute named “user” and redirects to DisplaySessionAttributeServlet, which retrieves and displays the attribute.
  • Application Scope Example:
  • The ApplicationAttributeServlet sets an application attribute named “appName” and redirects to DisplayApplicationAttributeServlet, which retrieves and displays the attribute.

Homepage

Readmore