ContextAttribute in Servlet

ContextAttribute in Servlet


Posted in : Java Posted on : June 24, 2011 at 6:58 PM Comments : [ 0 ]

In this section we will discuss about the contextAttributes in java.

ContextAttribute in Servlet

In this section we will discuss about the contextAttributes in java.

Example :

ServletContextAttribute.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextAttribute extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
HttpSession session = req.getSession(true);
Integer count = 
(Integer) getServletContext().getAttribute("total");
if (count == null)
{
count = new Integer(1);
}
else
{
count = new Integer(count.intValue() + 1);
}
getServletContext().setAttribute("total", count);
pw.println
("<html><head><title>Context Attribute</title></head>");
pw.println
("<h1>Session Details:</h1>");
pw.println
("Time of the Session Created: " + new Date(session.getCreationTime())
+ "<br/>");
pw.println
("Last time accessed : " + new Date(session.getLastAccessedTime()) 
+ "<br/>");
pw.println("You are visiting "+ count+" time");
pw.println("</body></html>");
}
}

web.xml

<web-app>
<display-name>contextAttribute</display-name>
<servlet>
<servlet-name>ServletContextAttribute</servlet-name>
<servlet-class>ServletContextAttribute</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextAttribute</servlet-name>
<url-pattern>/ServletContextAttribute</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute the above example you will find the following output, in the output you will see that the how much time you will execute the program your visiting time will vary according to the execution.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics