Servlet Scopes and attributes:
For the fundamental servlet attribute scopes (request, session, and context):
write servlet code to add, retrieve, and remove attributes; given a usage
scenario, identify the proper scope for an attribute; and identify
multi-threading issues associated with each scope.
What is an attribute
Attributes allow data to be stored and used in inter servlet communication. For
example you might set some attributes in a login servlet that hands off to other
servlets for the actual processing. Attributes can also be used with the session
mechanism to preserve data between requests. The main methods associated with
attribute manipulation are
setAttribute
getAttribute
Attributes are stored using setAttribute as name/value pairs
with the signature
setAttribute(String name, Object value);
As you can see from this attributes are stored with a type of Object Take the
example of storing an Integer number as an attribute called count
setAttribute(“count”,new Integer(99));
To retrieve it you will need to cast back to the original type thus.
Integer count = (Integer)session.getAttribute("count");
Attribute in Servlet:
An attribute in servlet is an object that can be set, get or removed from one of
the following scopes:
request scope
session scope
application scope
The servlet programmer can pass informations from one
servlet to another using attributes. It is just like passing object from one
class to another so that we can reuse the same object again and again.
Attribute specific methods of ServletRequest, HttpSession and ServletContext
interface
There are following 4 attribute specific methods. They are as follows:
public void setAttribute(String name,Object object):sets
the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the
specified name.
public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters as an Enumeration of String objects.
public void removeAttribute(String name):Removes the attribute with the
given name from the servlet context.
The three attribute scopes (request,session,and context) represent different visibility and availability. The following table sums up their visibility.
Attribute Scope |
attribute | Scope of data |
ServletRequest | Duration of the request |
HttpSession | While the client is active |
ServletContext | The life of the web application |
In the context of a JSP page this means that the
implicit objects can be used as follows to set attributes in each scope.
request.setAttribute("username","marcus");
session.setAttribute("username","marcus");
application.setAttribute("username","marcus");
setAttribute and getAttribute are available to in request, session
and application scopes.
ServletRequest attributes:
The scope of ServletRequest is based on the fundamental nature of the
HttpRequest. The Servlet is executing and data is available to the executing
code. Once the request is complete there is no connection between the client and
the servlet and thus all data is effectively discarded. This is essential to the
stateless nature of the HTTP Protocol.
Session attributes:
The scope of HttpSession is based on extending the connection between the client
and the server code by implementing some way of allowing a state to exist
between requests. This depends on using a unique identifier based on a cookie,
which is called JSESSIONID. Data in the HttpSession scope is only available to a
single client and is not shared. Note that there is no guarantee of how session
attribute data is stored. Thus it might be stored in a file and not be available
if the server is restarted, or it could be stored in a database and thus be
available if the server is restarted.
ServletContext attributes:
Data in the ServletContext can be shared by any servlet of the same web
application. You have seen examples of data in this context previously with
information such as the database type or default language setting.
getAttributeNames:
Each of the objects has a getAttributeNames method that returns an enumeration
of the names of the attributes (no surprises there). If you didn't know what
attributes were available you could get the names and then loop through them
getting the values they contain.
Attributes and threading:
Servlet containers such as Jakarta Tomcat optimise performance by providing
execution through multiple threads. This optimises performance but introduces
the problem that the action of one thread might cause an inconsistent data
state, i.e. for example, if thread T1 sets an attribute A, and thread T2 sets
the same attribute A, there might be unpredictable results if thread T1 reads
attribute A back again.
The javax.servlet.SingleThreadModel interface:
This is a marker interface, i.e. it has no methods or fields but acts as a
marker to other code. The servlet specification guarantees that if a Servlet
implements this interface it will not execute the service method in more than
one thread simultaneously. This ensures that the doXXX methods are not executed
in more than one thread at a time.
Example of ServletContext to set and get attribute:
In this example, we are setting the attribute in the application scope and
getting that value from another servlet.
r4r.java
import
java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class r4r extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
context.setAttribute("company","IBM");
out.println("Welcome to first servlet");
out.println("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){out.println(e);}
}}
r4r2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class r4r2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
String n=(String)context.getAttribute("company");
out.println("Welcome to "+n);
out.close();
}catch(Exception e){out.println(e);}
}}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>r4r</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>r4r2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>