Share on Google+Share on Google+

Context attributes in Servlet

In this section you will study about the use of Context Attributes in Servlet.

Context attributes in Servlet


In this section you will study about the use of  Context Attributes in Servlet.

All Servlets belong to one servlet context. A Servlet Context attribute is used by all servlets and jsp in a context or web application. The getAtribute(), getAttributeNames(), setAttribute() and removeAttribute() methods dealing with context attributes are found in ServletRequest interface.

Here is an example which illustrates you about the context attributes.

Here is the code of

import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ContextAttribute extends HttpServlet 
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException, IOException 
  PrintWriter out = response.getWriter();
  HttpSession session = request.getSession(true);
  Integer totalTimes = 
  (Integer) getServletContext().getAttribute(
  if (totalTimes == null)
  totalTimes = new Integer(1);
  totalTimes = new Integer(totalTimes.intValue() + 1);
  getServletContext().setAttribute("total", totalTimes);
"<html><head><title>Use of Context Attribute</title></head>");
"<h1>Details of the session:</h1>");
"Session Creation time: " new Date(session.getCreationTime())
"Last access time: " new Date(session.getLastAccessedTime()) 
"Total number of visits: " + totalTimes + "<br/>");

In the above example, define the session by HttpSession session = request.getSession(true). An Integer variable totalTimes is passed to getServletContext().getAttribute("total"). If totalTimes is set to null, set totalTimes = new Integer(1), otherwise increment by one, the totalTimes and then call the method getServletContext().setAttribute("total", totalTimes).

Here is the output.

On this page you visited first time. Therefore it is showing total number of visits : 1. But after refreshing, the value of Last access time is changed and number of visits changed to 2

Download Source Code



Posted on: August 20, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Context attributes in Servlet  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image