JSP session attributes - setting

I have a file called index.jsp. This contains three links in the below format:


<a href="X.jsp" onclick="<%session.setAttribute("category","Sports");%>" ><img src="categoryOne.gif" />

Then in the destination file i.e. X.jsp i read in the variable

However, the value the attribute is set to is whatever last occured on the index page, regardless of it being clicked.

Is there a way to do this using JSP or is the easiest way to set a parameter “onClick”? if so how do i do this using a link?

When a JSP page is called, by clicking a link such as index.jsp, the following happens, in this order:

1- Server checks to see if the .jsp has already been compiled and whether or not it has changed since it was last compiled.

*- We’ll assume the .jsp has not been previously compiled.

2- Server runs the jsp through the Jasper compiler, which interprets the jsp into Java code, anything that is not Java (CSS, HTML, JavaScript, etc) is placed in a String.

3- The Java code is compiled and executed.

4- The results are placed in the response and sent to the user.

So, your statement: “session.setAttribute(“category”,“Sports”);” is executed before the the HTML is sent to the user, and does exactly what it says: sets the session attribute “category” to “Sports”, I assume you have “category” set this way multiple times and when you get to X.jsp, category is always the last one.

If you were to right click index.jsp and select “view page source”, you would see


<a href="X.jsp" onclick="" ><img src="categoryOne.gif" />

because the setAttribute was made into a separate command and executed before the page was sent to you.

Jasper would (essentially) interpret your line into Java as


out.print( "<a href=\\"X.jsp\\" onclick=\\"" );
session.setAttribute("category","Sports");
out.println( "\\" ><img src=\\"categoryOne.gif\\" />" );
// out is the PrintWriter obtained from the HttpResponse, destined to be sent to the user.

How to address this?

Here’s one solution


index.jsp
<a href="X.jsp?category=Sports"><img src="categoryOne.gif" /></a>

X.jsp
<&#37; String category = request.getParameter( "category" ); %>
(if you really want category as a session attribute, promote it at this point: )
session.setAttribute( "category", category );

Thankyou for such a detailed response! It works and I understand it a bit better now aswel. Much appreciated!

I would never take as much time as rushku to give great response like that! But, in any case it seems like you need to understand between Client Side Programming vs Server Side Programming. I’m sure if you google “Client Side Programming vs Server Side Programming”, you’ll understand more about it.

Is there a way of setting two parameters from a link e.g.:

example.html?param1="this"?param2="that"

example.html?param1=this&param2=that