Sep 18 2009

Difference between request.getAttribute and request.getParameter

Okay, so going by the name of this blog, one post regarding request.getAttribute was due, and here it is. It’s a newbie question which I will answer in this post.

Difference between request.getAttribute() and request.getParameter()

First of all, what is a parameter? If you are posting a form to the server (using get or post), then the name/value pairs are passed as parameters. e.g.: Your form looks like this:


<form method="post" action="/blah/"  name="loginForm">

Email ID:
<input name="email" id="email"type="text"/> <br/>
Password:
<input id="password" name="password" type="password" />
<input type="submit" value="LOG IN"/>
</form>

When this form is posted to the server, to fetch the values of “email” and “password” in your serlvet, you would need to use:

String email=request.getParameter("email");
String password=request.getParameter("password");

Note that the request.getParameter() method returns you a String. Simple enough!

Coming to request.getAttribute(), first let us look at what a request attributes. A request object can store objects in its attribute, which can be set as

request.setAttribute("user", userObject);

This is typically required when your servlet needs to pass on an object to another servlet/jsp. And the servlet needing this object can get it throught request.getAttribute(“blah”);
Note that this returns an object, which will need to be type-casted back. i.e. In your servlet, you will need to use the a similar code as:

User user = (User)request.getAttribute("user");

In this way, you can get back the object in your present servlet/jsp which you stored in another servlet/jsp.
Also note, that attributes can be passed in the request only on server, and cannot be passed to the client in this way.