Difference Between the Request Attribute and Request Parameter

  • Request parameters are the result of submitting an HTTP request with a query string that specifies the name/value pairs, or of submitting an HTML form that specifies the name/value pairs. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using getParameter(). Parameters are Strings, and generally can be retrieved, but not set.
  • Let’s take a real example, you have one html page named htmland JSP page named Register.jsp. The RegisterForm.html contains a form with few parameters for user registration on web application and those parameters you want to store in database.

<html>

<body>

<form name=”regform” method=”post” action=”../Register.jsp”>

<table ID=”Table1″>

<tr>

<td>

First Name : <input type=”text” name=”FIRSTNAME” size=”25″ value=””>

</td>

</tr>

<tr>

<td>

<input type=”Submit” NAME=”Submit” value=”Submit” >

</td>

</tr>

</table>

</form>

</body>

</html>

When user will enter first name in the text filed and press submit button, it will callRegister.jsp page. Now you want the value entered in text field by user in jsp/servlet so there you use request.getParameter() method.

<%

String lFirstName = request.getParameter(“FIRSTNAME”);

……………….

%>

On the server side, the request.getParameter() will retrieve a value that the client has submitted in the First Name text field. Using this method you can retrive only one value. This method i.e. getParameter method is in ServletRequest interface which is part of javax.servlet package.

Request attributes (more correctly called “request-scoped variables”) are objects of any type that are explicitly placed on the request object via a call to the setAttribute() method. They are retrieved in Java code via the getAttribute() method and in JSP pages with Expression Language references. Always use request.getAttribute() to get an object added to the request scope on the serverside i.e. using request.setAttribute().

Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern. For example, you want to take values from database in one jsp/servlet and display them in another jsp. Now you have resultset filled with data ready in servlet then you use setAttributemethod and send this resultset to another jsp where it can be extracted by using getAttributemethod.

Once a servlet gets a request, it can add additional attributes, then forward the request off to another servlet for processing. Attributes allow servlets to communicate with one another.