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
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
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: August 20, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles