Friday, April 13, 2012

Parameter Passing : HTML--> JSP--->JSP

The most frequent question in JSP tut or Wb design is that ..
"Is it possible to pass a parameter between JSP pages IF the parameter hasn't been set in HTML tags?"

There are a few ways to pass information from one JSP page to another.

1. Hidden values.

Simply write the data to an input field within a form with the type 'hidden', e.g.

<input type="hidden" name="mydata" value="<%=thedata%>">

Data written thus will get posted back when the relevant form is submitted. This can be a useful way to 'carry along' information as the user fills out a series of dialogs as all state is user side and the back and forward buttons will work as expected.

2. URL writing.

Attach parameters to URLs in links on the page, e.g.

<a href="another.jsp?mydata=<%=thedata>>Go!a>

This also maintains the state with the client while removing the need for a form element to be submitted.

3. Cookies.

Should speak for itself.The state is still user side but is now handled by a cookie. More fragile in some ways since some people disable cookies. Also the back and forward buttons may do unexpected things if you are not careful

4. Server side (session)

Finally you could store the data in a session variable on one JSP and retrieve it on the next, e.g.

session.setAttribute(String key, Object value)

and

session.getAttribute(String key)

Here the state is kept server side which has some benefits (the user can browse away and return without losing his place, but tends to make the back and forward buttons in the browser a bit unreliable unless you are careful. Also the value is available to all pages.

It does however have the advantage that the information is never sent to the client and is thus more secure and more tamper proof.


You usually pass data between servlet/JSP or JSP pages in scoped attributes (in request, session or application). E.g. request.setAttribute("key", data) can set "key" attribute in one JSP, andrequest.getAttribute("key") gets you this data in other JSP (if multiple JSPs are processing same request).

It is possible to create fake parameters by wrapping your request, and overriding getParameter and similar method, if that is what you really need.



Let's do some expamle :

How to set in send.jsp
===============================
<% request.setAttribute("AttributeName","This is the Attribute value."); String strViewPage="SetAttributeMethod1.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage); if (dispatcher != null){ dispatcher.forward(request, response); } %>

===============================
How to get the value in recv.jsp?
<% out.println(request.getAttribute("AttributeName")); %>

========================================

Hope it helps..

Cheers
Dipankar

No comments:

Post a Comment