Java Servlet Attributes

Servlet Attributes in Java

In this article, I am going to discuss Servlet Attributes in Java Application. Please read our previous article where we discussed ServletContext Interface in Java Web Application. At the end of this article, you will understand the following pointers.

  1. Why Attributes in Servlet?
  2. Request Attribute in Servlet
  3. Session Attribute in Servlet
  4. Application Attribute in Servlet
  5. Methods used in Attributes
  6. Example: Attributes in Servlet
  7. Difference Between ServletConfig and ServletContext
Why Attributes in Servlet?

The attribute is a Java object which can be set, get, or removed. It provides more visibility and accessibility to the data of the application. Scopes to set, get, or remove an object are:

  1. Request attribute
  2. Session attribute
  3. Application attribute
Request Attribute in Servlet

The request scope is used while processing the results of a submitted form. We can set and get Request Attributes with an object. For example:

Request.setAttribute(“cars”, CarsObject);
Request.getAttribute(“cars”);

Request Attribute in Servlet

Session Attribute in Servlet

Session Attribute is used to create the session by the Web Container when a user visits the web application. For example:

HttpSession session=request.getSession();
Session.setAttribute(“cars”,CarsObject);

Session Attribute in Servlet

Application Attribute in Servlet

Application Attribute scope persists until the application is delayed. It is also known as the context attribute. Any servlet within the same application can have access to context attributes. For example:

getServletContext().setAttribute(“dbUrl”,”jdbc:mysql://localhost:3306/login”);
getServletContext(),getAttribute(“dbUrl”);

Application Attribute in Servlet

Methods used in Attributes
  1. public void setAttribute(String name, Object object): It is used to set the given object in the application scope.
  2. public Object getAttribute(String name): It is used to return the attribute for the specified name.
  3. public Enumeration getInitParameterNames(): It is used to return the names of the context’s initialization parameters as an Enumeration of String objects.
  4. public void removeAttributes(String name): It is used to remove the attribute with the given name from the servlet context.
Example: Attributes in Servlet

In this example, we are setting the attribute in the SetAttributeServlet.java in application scope, request scope, and session scope and getting that value from another servlet SetAttributeServlet.java.  Here I used the request.getSession method to return a session object. The setAttribute() method allows you to specify a name first and a value second and will set it in the session. When you want to get an attribute value saved in a session you can retrieve it using the attribute name. Bypassing the name in the getAttribute method you will return the value. removeAttributes takes the attribute name and then removes them from the session.

GetAttributeServlet.java

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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;
import java.io.IOException;
import java.io.PrintWriter;

public class GetServletAttribute extends HttpServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // get application-scoped attribute
        String applicationScope = (String)req.getServletContext().getAttribute("name");

        // get session scoped attribute
        HttpSession session = req.getSession();
        String sessionScope = (String)session.getAttribute("name");
       
        // get request scoped attribute
        String requestScope = (String)req.getAttribute("name");

        // print response
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.write("<html><body>");
        out.write("<h2>Servlet attributes example: applicationScope, sessionScope and requestScope</h2>");
        out.write("<p>applicationScope: " + applicationScope + "</p>");
        out.write("<p>sessionScope: " + sessionScope + "</p>");
        out.write("<p>requestScope: " + requestScope + "</p>");
        if(session != null) {
        session.removeAttribute("name");}
    }
}

SetAttributeServlet.java

import javax.servlet.RequestDispatcher;
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;
import java.io.IOException;

public class SetServletAttribute extends HttpServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // set application scoped attribute
        req.getServletContext().setAttribute("name", "application scoped attribute");

        // set session scoped attribute
        HttpSession session = req.getSession();
        session.setAttribute("name", "session scoped attribute");

        // set request scoped attribute
        req.setAttribute("name", "request scoped attribute");

        // send redirect to other servlet
        RequestDispatcher rd = req.getRequestDispatcher("servlet2");
        rd.forward(req, resp);
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ServletAttributesExample</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>SetServletAttribute</servlet-name>
    <servlet-class>SetServletAttribute</servlet-class>
  </servlet>
     <servlet>
    <servlet-name>GetServletAttribute</servlet-name>
   <servlet-class>GetServletAttribute</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>SetServletAttribute</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>  
  <servlet-mapping>
    <servlet-name>GetServletAttribute</servlet-name>
    <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>
      
</web-app>

Output

Servlet Attributes

Difference Between ServletConfig and ServletContext
ServletConfig ServletContext
It is a unique object per servlet. It is a unique object for a complete application.
It is used to provide the init parameters to the servlet. It is used to provide the application level init parameters that all other servlets can use.
Attributes in the ServletConfig object cannot be set. We can set the attributes in ServletContext that other servlets can use.

In the next article, I am going to discuss Servlet Scopes. Here, in this article, I try to explain Java Servlet Attributes with Examples. I hope you enjoy these Attributes in the Servlet article.

Leave a Reply

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