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
<% String category = request.getParameter( "category" ); %>
(if you really want category as a session attribute, promote it at this point: )
session.setAttribute( "category", category );