Thursday, 17 January 2013

Difference between attribute and parameter in Java

1. A "parameter" is a form field name/value pair passed from the HTML side of the world
   An "attribute" is a Java object name/value pair passed only through the internal JavaServer   processes. (I.e. it can come from a JSP or servlet but not an HTML page.) 

2. Parameter value is a String whereas attribute value is Object.

2. Parameters come from the client request.

 where as Attributes are set by the server side. For example, you can set a session or request attribute called userId to  indicate the current user

4. Parameters are read only i.e. generally can be retrieved, but not set. whereas 
 Attributes are read/write .You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern.


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.

Note :
Later if you want, you can set parameters in request scope, which will be accessed in other included/forwarded servlet/JSP while using RequestDispatcher mechanism or can set parameter in session scope or application leval scope.Be careful here: there is no ServletRequest.setParameter() or HttpServletRequest.setParameter() method, nor is there a RequestDispatcher.addParameter() of RequestDispatcher.setParameter() method.