简体   繁体   中英

If else statements inside jsp

I have a following problem - if else statements do not work in JSP, and to be honest I have no idea why. Basically I try to change the placeName depending on what number is stored in a string called place. After printing the values in the browser I can see the value is not changed. I am sure it is something simple but... Maybe some one had similar problem before?

<%
//requests the strings sent by previous page
String year = request.getParameter("year");
String place = request.getParameter("place");
out.print(year);
out.print(place);

String year2 = request.getParameter("year2");
String place2 = request.getParameter("place2");
//out.print(year2);
//out.print(place2);

if (place == "1")
{
placeName = "Belmullet";
}
else if (place == "2")
{
placeName = "Birr";
}
...more statements here...
else if (place == "15")
{
placeName = "Shannon airport";
};
%>

change the if condition:

if (place == "1") {

}

by

if ("1".equals(place)) {

}

and the same way for the other if conditions.

This SO question may helps you to learn the difference between == and equals() .

It's because you're comparing Strings using ==. Instead, use the .equals() method.

The == operator tests to see if two object references refer to the exact same instance of an object.

The .equals() tests to see if the two objects being compared to each other are equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM