What is an attribute?
In servlet & JSP (V), we learned how the listener of servletcontext creates an object after obtaining the context initialization parameters, and how to store the object as an attribute to servletcontext, so that other parts of the web application can obtain the object. An attribute is an object that is set (or bound) to the other three servlets.
-Sservletcontext, httpservletrequest (or httpservletresponse), and httpsession In the API object. You can simply think of it as a name/value pair (name is a string and value is an object) in the ing instance object ). In reality, we don't care how it is implemented, but only about the attribute scope. In general, it depends on how long it can survive.
Differences between attributes and Parameters
Properties are not parameters. The differences between them are shown in table 1.
|
Attribute |
Parameters |
Type |
Application/Context Request Session (Note: servlet-specific attributes are not available. You only need to use instance variables .) |
Application/context initialization parameters Request Parameters Servlet initialization parameters (Note: There is no session parameter .) |
Setting Method |
Setattribute (string name, object value) |
Application and Servlet initialization parameters cannot be set. They are all set in Web. xml. |
Return type |
Object |
String |
Obtain Method |
Getattribute (string name) (Note: Do not forget to forcibly convert because the return type is object) |
Getinitparameter (string name) |
Table 1 differences between attributes and Parameters
Three scopes: context, request, and session
Context attribute. Each part of the Web application can be accessed. Session attribute. Only the part that can access a specific httpsession can be accessed. The request attribute can only be accessed if it can access a specific servletrequest. The specific scopes are shown in table 2.
|
Accessibility (Who can see it) |
Scope (How long can it survive) |
Applicability |
Context) (Not thread-safe) |
All parts of a web application, including servlet, JSP, and servlet-contextlistener. |
The life cycle of the servletcontext, which means the life cycle of the subordinate application. If the server or application is disabled, the context is revoked and its properties are also revoked. |
Resources that you want the entire application to share, including database connections, jndj lookup names, and email addresses. |
Httpsession) (Not thread-safe) |
Access all servlets or JSPs of a specific session. Note that a session is extended from a customer request to multiple requests that may span the same customer. These requests may reach multiple servlets. |
The lifetime of a session. The session can be undone through programming, or it may be undone only because of timeout. |
Resources and data related to customer sessions, not just resources related to a request. It needs to complete a continuous session with the customer. Shopping cart is a typical example. |
Request) (Thread-safe) |
All parts of the request object can be directly accessed in the application. Basically, this means that the JSP and Servlet (using requestdispatcher) that receive the forwarded request, and the listener related to the request. |
The lifecycle of the request. This description continues until the service () method of servlet ends. That is, the life cycle of the thread/stack processing the request. |
Transmits model information from the Controller to the view, or any data specific to the customer request. |
Table 2 attribute Scope
The context scope is not secure.
Because each part of the application can access context attributes, this means that there may be multiple servlets. Multiple servlets indicate that you may have multiple threads. Because the requests are processed concurrently, each request is processed in a separate thread. For example, the following statement:
getServletContext().setAttribute("boo","12");getServletContext().setAttribute("foo","24");out.println(getServletContext().getAttribute("boo"));out.println(getServletContext().getAttribute("foo"));
During the first running of a complex project, the expected result may be 12 24, and the second output may be 12, 36. Possible cause: servlet A sets the context attribute "boo" to "12", and "foo" to "24 ". Then thread B, that is, Servlet B becomes the active thread (at this time, thread a returns to the running but not running status ), set the value of the context attribute "foo" to "36" (Value "24" is lost ). At this time, thread a becomes the active thread again. It gets the value of "foo" and the result is 36.
How to Ensure thread security for context attributes?
Since the context attribute is NOT thread-safe, how can we improve it? Some people say that the synchronous service is used. Modify the doget method as follows:
public synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter();getServletContext().setAttribute("boo","12");getServletContext().setAttribute("foo","24");out.println(getServletContext().getAttribute("boo"));out.println(getServletContext().getAttribute("foo"));}
Add the synchronized keyword to the doget method. However, this method means that the servlet can only run one thread at a time, but it cannot prevent other servlets or JSPs from accessing this attribute. The synchronous service method prevents other threads in the same servlet from accessing the context attribute, but cannot block access from another servlet. Therefore, you do not need to lock the servlet, but the context, that is, you should make the following changes:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter();synchronized(getServletContext()) {getServletContext().setAttribute("boo","12");getServletContext().setAttribute("foo","24");out.println(getServletContext().getAttribute("boo"));out.println(getServletContext().getAttribute("foo"));}}
The general method to protect context attributes is to synchronize the context object itself. If everyone accessing the context must first obtain the lock of the context object, this ensures that only one thread can obtain or set the context attribute at a time. However, this method works only when other code that processes these context attributes synchronizes servletcontext. If a piece of code does not have a request lock, the code can still freely access context attributes.
Is the session property secure?
It seems that the session has not been introduced yet. The session will be discussed in the next article. In fact, a session is an object used to maintain the session state with a user. For multiple requests of the same user, sessions are stored persistently across these requests. Let's take a look at the situation where there is only one user. If there is only one user and one customer has only one request at a time, does this indicate that the session is thread-safe? Will one user have multiple requests at a time? Yuan Fang, what do you think?
A user may open a new browser window. In this case, the container still uses the same session for one user, even though it comes from another browser instance. Therefore, session attributes are NOT thread-safe. So how can we protect these session attributes from the destruction of multiple threads? You just need to synchronize all the codes that access these session attributes like the context attributes. So, who should synchronize? Must be synchronized to httpsession! The Code is as follows:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter();HttpSession session = request.getSession();synchronized(session) {session .setAttribute("boo","12");session .setAttribute("foo","24");out.println(getServletContext().getAttribute("boo"));out.println(getServletContext().getAttribute("foo"));}}
To prevent synchronization from causing a large amount of overhead, you must complete the synchronization target in the shortest time, so that the synchronization block should be as small as possible.
Reprinted please indicate the source: http://blog.csdn.net/iAm333