Attribute in Servlet

In this post, you will learn important line
  • What are Attributes?
  • Why are Attributes needed?
  • What are the differences between attributes and parameters?

An attribute in servlet is an object that can be set, get or removed from one of the following scopes:

  1. request scope
  2. session scope
  3. application scope

				
 Application Scope
ServletContext sc=getServletContext();
sc.setAttribute("user", "Mithilesh");
sc.getAttribute("user");
sc.removeAttribute("user");

Note:  sc -context object
	user - attribute name
	Mithilesh -attribute value
	getAttribute-getting an attribute
	removeAttribute-remove attribute
--------------------------------	
Request Scope-
--------------------------------
request.setAttribute("user","Mithilesh");
request.getAttribute("user");
request.removeAttribute("user");

Note request- ServletRequest object

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface


There are following 4 attribute specific methods. They are as follows:

  1. public void setAttribute(String name,Object object):sets the given object in the application scope.
  2. public Object getAttribute(String name):Returns the attribute for the specified name.
  3. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
  4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

Example
	
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();
        sc.setAttribute("user","mithilesh");	//setting attribute on context scope
    }
}

How to get an attribute

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

public class Second extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();
       //getting attribute from context scope 
        String str = sc.getAttribute("user");
        out.println("Welcome"+str);  // Prints : Welcome Mithilesh   
    }
}

What are the differences between attributes and parameters?

Differences between attributes and parameters:

  1. Parameters are request data which are stored by the server in the ServletRequest object so that it can be read by the Servlets during processing.
  2. Attributes are data which are stored by a Servlet in ServletRequest object so that it can be shared by others Servlets which are participating in the processing of the same request.
  3. Parameters are only read by the Servlets i.e. Servlets can't update or remove them. Attributes are added, removed, replaced and read by the Servlets.
  4. Parameters are of String type. Attributes can be any type of objects.
  5. Parameters are usually required in the processing of each request but attributes are required only when more than one Servlet participate in the processing of a request.

Following analogy will make the difference clear between attributes and parameters. Lets say you went to XYZ company for walk-in. When you reached there, you were told that the selection process has three rounds.

  1. Document Verification
  2. Technical Interview
  3. HR Interview

For the first round, you presented you documents for verification. The verifier gave a number to your document file, wrote verified and signed on it.

This numbered file was sent to the technical interviewer, who called you according to your file number, took the interview and wrote the grade on the file and signed on it.

This file was sent to the HR manager for interview. This file contained two types of information. First, information provided by you through your documents. This information is read only, It is parameter. Second, information added by the verifier and technical interviewer so that it can be shared with the HR Manager. It is attribute. If only one person would be responsible for the selection, no attribute was required. I hope that now you would have understood the differences between the attributes and parameters well.

Now we should know how we can use attributes. Well, ServletRequest interface provides following methods for attributes.

setAttribute(): this method is used by a Servlet to set an attribute in request scope i.e in ServletRequest object. It has following syntax:

public void setAttribute(String name, Object value);

getAttribute(): this method is used by a servlet to obtain the value of an attribute from request scope. It has following syntax:

public Object getAttribute(String name);

getAttributeNames(): this method is used by a servlet to obtain the name of all request scope attributes. It has following syntax:

public Enumeration getAttributeNames();

removeAttribute(): this method is used by a servlet to remove a request scope attribute. It has following syntax:

public void removeAttribute();

Difference between ServletConfig and ServletContext

The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application.