JSTL if tag for equal strings

JavaJspWebsphereJstlJsp Tags

Java Problem Overview


I've got a variable from an object on my JSP page:

<%= ansokanInfo.getPSystem() %>

The value of the variable is NAT which is correct and I want to apply certain page elements for this value. How do I use a tag to know the case? I tried something like

<c:if test = "${ansokanInfo.getPSystem() == 'NAT'}">      
   process  
</c:if> 

But the above doesn't display anything. How should I do it? Or can I just as well use scriptlets i.e.

<% if (ansokanInfo.getPSystem().equals("NAT"){ %>
process
<% } %>

Thanks for any answer or comment.

Java Solutions


Solution 1 - Java

Try:

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).

Solution 2 - Java

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

Solution 3 - Java

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

> This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone. > > Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

Solution 4 - Java

You can use scriptlets, however, this is not the way to go. Nowdays inline scriplets or JAVA code in your JSP files is considered a bad habit.

You should read up on JSTL a bit more. If the ansokanInfo object is in your request or session scope, printing the object (toString() method) like this: ${ansokanInfo} can give you some base information. ${ansokanInfo.pSystem} should call the object getter method. If this all works, you can use this:

<c:if test="${ ansokanInfo.pSystem  == 'NAT'}"> tataa </c:if>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiklas RosencrantzView Question on Stackoverflow
Solution 1 - JavaAdam GentView Answer on Stackoverflow
Solution 2 - JavaPhaniView Answer on Stackoverflow
Solution 3 - JavaJörn HorstmannView Answer on Stackoverflow
Solution 4 - JavaJohanBView Answer on Stackoverflow