Servlets-Sharing of objects in scope

We have seen that servlets may interact by calling each other’s methods, redirecting, and dispatching (forwarding) their requests. Servlets may also communicate by accessing objects (attributes) which they have in common with other servlets. Attributes are available to servlets within the scope of request, session, and application. This section describes the ways in which objects may be shared at these different levels.

Request level scope

We have already seen how request level scope can be implemented, through the RequestDispatcher forward method. Here, the request object stays in scope as it is passed from resource to resource.

But in addition to the objects that are natively part of the request, how do we pass other objects along with the request? We do this by using the request.setAttribute method. This method allows us to store an object type by name, which we can later reference by that name as we forward the request to another servlet for processing. The object we store can be of a user-defined type, such as a JavaBean, which is accessible within the called servlet. Objects at this level remain in scope as long as the request is active, which is until the server sends back the response.

Code below shows how we can set a request attribute called count. This code would be found in a calling (forwarding from) servlet in the request dispatching process.

//calledCount is the value we are storing to the attribute
int calledCount;
//Cast our int object to Integer, because cannot store native types
request.setAttribute("count", new Integer(calledCount));

Code below shows how we can retrieve this attribute. This code would be found in a called (forwarded to) servlet in the request dispatching process.

//getting count attribute, and casting back to an int
Integer tempCount = (Integer)request.getAttribute("count");
int calledCount = tempCount.intValue();
out.println("Called count is: " + calledCount);

Read Session Level Scopes also
Servlets-Sharing of objects in scope Reviewed by 1000sourcecodes on 00:30 Rating: 5
Powered by Blogger.