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
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.