Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter without use of HTML forms in JSP

Tags:

java

jsp

I have done some research, and majority of the examples I have found use forms (obviously for user input) to collect data which is then passed to another JSP page through the request object.

My question is: Is it possible to pass a parameter between JSP pages if the parameter hasn't been set in HTML <form> tags?

like image 382
Lycana Avatar asked May 14 '09 09:05

Lycana


2 Answers

There's no way a JSP page can tell the difference between a manually constructed GET url, e.g.:

<a href="/foo.jsp?bar=baz">Go to the next JSP page</a>, versus something like:

<form method="get" action="/foo.jsp">
<input name="bar" value="baz">
</form>

Either way it can be accessed through getParameter or getParameterValues

Is that what you're asking?

like image 97
Matthew Flaschen Avatar answered Oct 15 '22 18:10

Matthew Flaschen


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.

like image 23
Kris Avatar answered Oct 15 '22 19:10

Kris