Context attributes in Servlet

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

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 ContextAttribute.java

import java.io.*;
import java.io.IOException;
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 
  {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  HttpSession session = request.getSession(true);
  Integer totalTimes = 
  (Integer) getServletContext().getAttribute(
"total");
  if (totalTimes == null)
  {
  totalTimes = new Integer(1);
  }
  else
  {
  totalTimes = new Integer(totalTimes.intValue() + 1);
  }
  getServletContext().setAttribute("total", totalTimes);
  out.println
(
"<html><head><title>Use of Context Attribute</title></head>");
  out.println
(
"<h1>Details of the session:</h1>");
  out.println
 (
"Session Creation time: " new Date(session.getCreationTime())
 + 
"<br/>");
  out.println
(
"Last access time: " new Date(session.getLastAccessedTime()) 
"<br/>");
  out.println("</body></html>");
  out.println
(
"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