What is a property?
Properties and Parameters
3 Scopes for a property
Property API
Bad side of the property
1, in the end what is the attribute (Attribute)?
A property is an object that can be set (bound, also called binding) to another three Servlet API objects ServletContext, HttpSession, HttpServletRequest. You can simply think of it as a name/value pair, named String, and the value is object. In practice, we do not know or care about how it is implemented, but what we care about is the scope in which the property resides.
2, the attribute is not a parameter (Parameter)!
Parameters in note 1--Request parameters:
Parameter--servlet initialization parameters in note 7:
And, context initialization parameter parameters:
3.3 Scopes for attributes:
- The ServletContext property (context property) is accessible to every part of the--web app
- HttpSession Properties (Session properties)--access to specific httpsession parts
- HttpServletRequest Property (Request attribute)--access to a specific portion of ServletRequest
4, set, access the properties of the api--per interface (ServletContext, HttpS ... ) is exactly the same as the property API
For enumeration, see Java-enumeration Summary by IAMTJW
5, the bad side of the property. •. ```.. ``.. `.`.`...`..
- Context properties are not thread safe! A context property may be changed and accessed by multiple servlets at the same time. The bad solution is to add synchronized to doget (or other methods), which does not solve the problem because synchronized can only prevent other threads in the same servlet from accessing the context properties. But you cannot prevent another servlet from accessing it. For ynchronized see Java synchronized detailed by Gang.wang.
The correct approach is to lock the context instead of the servlet. How to achieve it? Look at the following code:
- is the session property thread-safe? No, because the user may open several browser windows ... Solutions are similar:
- only request properties and local variables are thread-safe!
It is important to note that the instance domain of the servlet is not thread-safe, unless Singlethreadmodel is implemented, or synchronous service methods, but this is a very bad practice that makes the Web application inefficient, so a servlet should not have an instance variable at all. There should also be final, if you really need to share something in multiple threads, then add it to the appropriate scope.
Head first Servlets and JSP note 9: Scope of properties, thread safety