May 14, 2012 0
Types Of Attributes In Servlet Servlet Scopes And Attributes Saving Data In A Servlet Attributes Interview Question
Types Of Attributes In Servlet
An attribute is an object used to pass some value from one servlet to another.An attribute in a servlet can be set at various scopes depending upon the visibility in the web application.As we know that there are three scopes at servlet level in the application.Theses scopes are :
An attribute can be set on either of the scopes depending on the situation we want access the attribute value either at request,session or application level.
When we want the value of an attribute o be accessed at request level we use request attributes and likewise for session and application.
Types of attributes in servlet can be explained on the basis of scope it belongs to :
1.Request Attributes can be set or get as demonstrated below in the code :
2.Session Attributes can be set or get as shown below :
3.Application Attributes can be set or get as below :
Now comes the question where to use what?
Request Attributes : If we want to retain or communicate a value across servlets where request does not change,we use request attributes.This can be the situation where include or forward is happening between the servlets in a web application.In such cases where we want to communicate a value across servlets we can use request attributes which when set from one servlet can be get in other servlets.
Session Attributes : In cases where user specific data has to be retained or communicated, we use session attributes.We use session attributes when we do not want a user’s data to be interfered by other users.It should be noted that these attributes can be retrieved even when redirect is happening provided the session is maintained .
Application Attributes : In cases where some value has to be set at application level and all the entities in the web application can read that value we use application attributes.
Number of View :251