为什么 String.equals() 方法在 JSTL Core 标记 <c:if> 中不起作用?

Why doesn't String.equals() method work inside the JSTL Core tag <c:if>?

代码的用途:验证用户输入的字符串。如果用户输入他的姓名,存储为 'n',存储为 "James",则显示消息 "Validated!"。 (一个单独的 HTML 表单负责输入字符串)

虽然没有任何错误,但标签内的测试失败,无论输入字符串是否为 "James" 都不会显示消息。

<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>

如果我在大括号内用 true 替换测试条件,则 if 条件通过并显示消息 "Validated!"。

为什么 equals() 方法在 JSTL 标签内不起作用?

  1. 您尚未将变量保存到 范围

你必须这样做,否则 EL 将看不到你的变量。

将变量保存到请求范围:

<c:set var="n" value="${param.n}" scope="request"/>
<c:set var="t" value="James" scope="request"/>

您需要使用 EL 的 eq 运算符而不是 Java 的 .equals().

像这样更改您的代码:

<c:if test="${t eq n}"> 
  <c:out value="Validated!"/>
</c:if>

P.S。您的 JSP 文件包含不良做法的 scriptlet,并且该方法不安全。

按照描述将逻辑和视图分开会更好here

您可以这样使用普通的 == 比较运算符:

<c:if test="${t == n}"> 
    <c:out value="Validated!"/>
</c:if>

如果您需要比较字符串值而不是对象的属性,您可以这样做:

<c:if test="${t == 'Any string can be here'}"> 
    <c:out value="Validated!"/>
</c:if>