See the Tutorial List

Servlet: Introduction to Attribute

An attribute is an object that is used to share information in a web app. Attribute allows Servlets to share information among themselves. Attributes can be SET and GET from one of the following scopes :

  1. request
  2. session
  3. application

setting and getting an attribute


Servlet: How to SET an Attribute

public void setAttribute(String name, Object obj) method is used to SET an Attribute.

Example demonstrating Setting Attribute

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","Abhijit");	//setting attribute on context scope
    }
}

Servlet: How to GET an Attribute

Object getAttribute(String name) method is used to GET an attribute.

Example demonstrating getting a value of set 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();
 
        String str = sc.getAttribute("user");  //getting attribute from context scope
	
        out.println("Welcome"+str);  // Prints : Welcome Abhijit   
    }
}