In the last post, you were told that more than one servlet can participate in the processing of a request. In such a case participating servlets may need to share their processing result with each other. Attributes facilitate this sharing of intermediate state of servlets during request processing.
Differences between attributes and parameters:
Following analogy will make the difference clear between attributes and parameters. Lets say you went to XYZ company for walk-in. When you reached there, you were told that the selection process has three rounds.
- Document Verification
- Technical Interview
- HR Interview
For the first round, you presented you documents for verification. The verifier gave a number to your document file, wrote verified and signed on it.
This numbered file was sent to the technical interviewer, who called you according to your file number, took the interview and wrote the grade on the file and signed on it.
This file was sent to the HR manager for interview. This file contained two types of information. First, information provided by you through your documents. This information is read only, It is parameter. Second, information added by the verifier and technical interviewer so that it can be shared with the HR Manager. It is attribute. If only one person would be responsible for the selection, no attribute was required. I hope that now you would have understood the differences between the attributes and parameters well.
Now we should know how we can use attributes. Well, ServletRequest interface provides following methods for attributes.
setAttribute(): this method is used by a Servlet to set an attribute in request scope i.e in ServletRequest object. It has following syntax:
getAttribute(): this method is used by a servlet to obtain the value of an attribute from request scope. It has following syntax:
getAttributeNames(): this method is used by a servlet to obtain the name of all request scope attributes. It has following syntax:
removeAttribute(): this method is used by a servlet to remove a request scope attribute. It has following syntax:
In addition to ServletRequest, two other interfaces of Servlet API, have these methods as you would come to know in later posts. In the next post we will cover practical example of RequestDispatcher.