Reputation: 270
Purpose of code: To validate an input string from the user. If the user inputs his name, stored as 'n', as "James" then the message "Validated!" is displayed. (A separate HTML form takes care of the input string)
Although there aren't any errors, the test inside the tag fails and the message is not displayed regardless of whether the input string is "James" or not.
<body>
<% String n = (String)request.getParameter("n");
String t = "James";
%>
Message <!-- Default message displayed to show that HTML body is read. -->
<c:if test="${t.equals(n)}">
<c:out value="Validated!"/>
</c:if>
</body>
If I were to replace the test condition with true inside the curly braces, the if condition passes and the message "Validated!" is displayed.
Why doesn't the equals()
method work inside the JSTL tag?
Upvotes: 1
Views: 1323
Reputation: 2367
You've to do this otherwise EL won't see your variables.
Save the variables to request scope:
<c:set var="n" value="${param.n}" scope="request"/>
<c:set var="t" value="James" scope="request"/>
You need to use EL's eq operator instead of Java's .equals()
.
Change your code like this:
<c:if test="${t eq n}">
<c:out value="Validated!"/>
</c:if>
P.S. Your JSP file contains scriptlets that is bad practice and the approach is insecure.
Would be even better to separate the logics and the views as described here
Upvotes: 2
Reputation: 8033
You can use normal ==
comparison operator in this way:
<c:if test="${t == n}">
<c:out value="Validated!"/>
</c:if>
If you need to compare string values rather than object's attribute, you can do this:
<c:if test="${t == 'Any string can be here'}">
<c:out value="Validated!"/>
</c:if>
Upvotes: 1