1. Object Properties scope: Who can see and use this property, and how long it can survive.
2. Apply context ServletContext Object scope:
- For the entire Web application, there is only one ServletContext object, and it can be accessed everywhere in the web app;
- The ServletContext object is created and instantiated by the Web container, and it can read/write properties simultaneously in multiple threads;
- is thread insecure, so the read/write of the property needs to be synchronously processed or deeply copied;
- When the Web container is closed, the ServletContext object is destroyed;
- Recommendation: In the ServletContext object to save as little as possible the data that will not be modified, the common method is to use a singleton mode to process the shared data.
3. HttpSession Object Scope:
- Used to maintain session state between the server and a customer. Set properties in the HttpSession object and cannot be accessed from anywhere in the web app;
- HttpSession objects exist during a user session and can only be accessed in a thread that processes requests belonging to the same httpsession;
- The HttpSession object's property access is theoretically thread-safe, but when a user opens multiple browser windows that belong to a process, where the access to the same HttpSession object is the same, multiple requests are made and more than one worker thread is required to process the request, which can cause thread insecurity At this time to read and write the properties of the thread synchronous processing, generally using synchronous block synchronized to deal with;
- When the session is destroyed, the HttpSession settings property is also destroyed;
4. HttpServletRequest Object Scope:
- The HttpServletRequest object is used for a single client request process. A new HttpServletRequest object is created for each request, executed by a single thread;
- So the HttpServletRequest object can only be accessed in one thread, it is thread-safe;
5, three objects in common: are built-in objects, are equivalent to the container, you can access properties, with the same property manipulation methods.
6. Different points of three objects:
- Scope size comparison: Servletcontext>httpsession object >httpservletrequest object;
- Duration of survival comparison: Servletcontext>httpsession object >httpservletrequest object;
- Resource consumption comparison: Servletcontext>httpsession object >httpservletrequest object;
- Thread Security Comparison: Servletcontext
Javaweb Chapter6 Object Scope