< Prev
Next >



Request Attributes



In this article, we are going to understand attributes associated with the current request made by the user. A request attribute is an object added to the request scope on the server side used for the request processing.

We can set and get the value of attributes associated with the request by using the methods of ServletRequest object. After setting some attributes with the current request, we can even pass this request from one to another Servlet in order to have a shared request processing by multiple Servlets.




Methods of ServletRequest to set, get and remove request attributes


Method Description
Object getAttribute(String str) This method gets an individual request attributes.
Enumeration getAttributesNames() This method gets all the named of request attributes.
void setAttribute(String name, Object value) This method sets the request attributes.
void removeAttribute(String name) This method sets the request attributes.





A Request Attribute Example


We are creating a webpage which asks the user to submit the details to check whether the user is eligible to get a premium facility or not, based on a condition -


after filling the details when submit button is clicked, the request is are dispatched or forwarded to the Servlet named FirstServlet (mentioned in the deployment descriptor file(web.xml).

Webpage1.jsp
<html>

<head>
<title>  Request Attributes Demo </title>
</head>


<body>
<b>Please enter your details to know if you are eligible to become our Premium member</b>
<br/>
<br/>
<br/>

<form action = "FirstServlet">
Name :<input type = "text"  name = "username"/>
<br/>

Salary <input type = "text"  name = "income"/>
<br/>

<input type = "submit" value = "submit" />
</form>

</body>
</html>





Creating a Servlet to set request attributes


We are creating a Servlet extending GenericServlet abstract class. GenericServlet class implements Servlet and ServletConfig interface, hence we can directly call the methods of ServletConfig within this Servlet.

Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2