Steven
Steven

Reputation: 3

JSP Sessions in If statments

Im having trouble understanding exactly how JSP works in terms of sessions...basically I am setting a session in a different JSP as follows:

<%
String category = request.getParameter("category");
session.setAttribute("category", category); %>

then in another page I am using if conditions to generate HTML based on which category has been posted e.g.:

 <% String category = (String) session.getAttribute("category");

if(category == "movie") { 
out.println("Movie Details"); 
} else if (category == "music") { 
out.println("Music Details"); 
} %>

But it seems neither of the two if statements are being hit but if I actually print out the category variable it is printed out correctly i.e. movie or music is being displayed. Is there some concept of sessions which I have not grasped? I have searched endless pages trying to find an answer for this :/ Thanks in advance.

Upvotes: 0

Views: 3808

Answers (2)

BalusC
BalusC

Reputation: 1108632

Bozho already answered the real cause of the problem. In Java, object values are to be compared by equals() method. Strings are objects, not primitives. Please note that this problem is not related to JSP, but to basic Java.

I just wanted to point out the correct way to go about this: use taglibs/EL. First install if necessary JSTL (Tomcat for example doesn't ship with it out the box) and then declare it in top of your JSP.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Your first code snippet can be achieved as follows:

<c:set scope="session" var="category" value="${param.category}" />

Your second code snippet can be achieved as follows:

<c:if test="${category == 'movie'}">Movie details</c:if>
<c:if test="${category == 'music'}">Music details</c:if>

or

<c:choose>
    <c:when test="${category == 'movie'}">Movie details</c:when>
    <c:when test="${category == 'music'}">Music details</c:when>
    <c:otherwise>Unknown category</c:otherwise>
</c:choose>

Yes, comparing strings by == is valid in EL. It will under the covers use equals() for that.

Upvotes: 1

Bozho
Bozho

Reputation: 597026

You are comparing strings the wrong way. You should use equals(..) instead of ==

== checks whether the instances are identical, while .equals(..) checks if the two strings have the same contents. You are very rarely interested in the former.

So, for objects (unlike primitives, where == is the way to go), use:

if (foo.equals(bar)) { .. }

When you have some experience with java and the servlet API, you should consider some best practices with JSPs. The most important one is not to write java code within JSPs. Here is an extensive explanation of how and why to do that.

Upvotes: 2

Related Questions