What is ServletContext?
When the Web container starts, it creates a corresponding ServletContext object for each Web application that represents the current web app. A reference to the ServletContext object is maintained in the ServletConfig object, and the developer can obtain the ServletContext object by Servletconfig.getservletcontext method when writing the servlet. Because all servlets in a web app share the same ServletContext object, communication can be achieved between servlet objects through ServletContext objects. ServletContext objects are also commonly referred to as context domain objects.
Do you think it's a bit of a conversation? Then do not worry, to understand ServletContext must and cookie, session to make a comparison, we pass a picture to illustrate:
You can think of it as a public space that can be accessed by all customers, that is, a customer can access D,b customers can also visit D,c customers can also access D.
Okay, now you know what's going on with ServletContext? So now that we know what ServletContext is, how do we use ServletContext? Normally we can use the ServletContext in three steps:
1. How to get ServletContext instances
This.getservletcontext ();
2. You can think of it as a table, this is very similar to the session, each row is a property,
servletcontext
Add Property setattribute (String Name,object obj), get the value getattribute (string name), return an Object, delete the attribute RemoveAttribute (string name);
3. Life cycle
The life cycle of a property in ServletContext ends with the start of the creation and the server shutdown.
So in web development, there are a lot of features need to use ServletContext, such as:
(1) Website counter (2) online number of Web sites (3) Simple chat system .....
Talking about ServletContext