【问题标题】:<c:when test="${action == view}"> never evaluates true on URL with ?action=view<c:when test="${action == view}"> 从不使用 ?action=view 在 URL 上评估 true
【发布时间】:2013-10-11 16:50:48
【问题描述】:

我有以下代码:

<%@ page language="java" session="true" contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<% 
request.setAttribute("action", request.getParameter("action"));
%>

<c:choose>
    <c:when test="${action == null}">
        NULL
    </c:when>
    <c:when test="${action == view}">
        VIEW
    </c:when>
</c:choose>

但是,当我使用 ?action=view 传递 URL 时,它不会显示 VIEW

我哪里错了?

【问题讨论】:

    标签: jsp jstl el


    【解决方案1】:

    EL 表达式${view} 正在页面、请求、会话或应用程序范围内查找该名称的属性,就像${action} 的工作方式一样。但是,您打算将其与字符串进行比较。然后,您应该使用引号使其成为真正的字符串变量,例如${'view'}。在普通的 Java 代码中也是如此。

    <c:choose>
        <c:when test="${action == null}">
            NULL
        </c:when>
        <c:when test="${action == 'view'}">
            VIEW
        </c:when>
    </c:choose>
    

    顺便说一句,使用 scriptlet 将请求参数复制为请求属性很笨拙。 You should not be using scriptlets at all。 EL 中的 HTTP 请求参数已通过 ${param} 映射提供。

    <c:choose>
        <c:when test="${param.action == null}">
            NULL
        </c:when>
        <c:when test="${param.action == 'view'}">
            VIEW
        </c:when>
    </c:choose>
    

    这样你可以摆脱整个&lt;% .. %&gt; 行。

    另见:

    【讨论】:

    • +1 小提示:我会使用空运算符而不是空值比较
    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 2013-08-04
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多