【问题标题】:expression language in jstl if statement not workingjstl if 语句中的表达式语言不起作用
【发布时间】:2021-08-02 17:12:02
【问题描述】:

我试图理解为什么这段代码在 tomcat 9 上运行时从不打印方法请求:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>Add Course</title>
</head>
<body>
    <c:if test="${\"POST\".equalsIgnoreCase(pageContext.request.method) && pageContext.request.getParameter(\"submit\") != null}">
        <%= request.getMethod() %>
    </c:if>
    <form method="post">
        Name: <input type="text" name="name"> <br>
        Credits : <input type="text" name="credits"> <br>
        <button type="submit" name="submit">Add</button>
    </form>
</body>
</html>

【问题讨论】:

    标签: eclipse jsp jstl tomcat9


    【解决方案1】:

    我的系统上当前没有安装 Tomcat 9,但它在 Tomcat 8.5 中运行良好,并且每当我发布表单时,Jetty 9.4.17 都会打印“POST”。

    然而,el 语言尽管在许多方面与 Java 相似并且能够调用 Java 函数,但它实际上并不是 Java。以更惯用的方式使用它,您会遇到更多的成功和一致性。在您的情况下,我很确定以下内容将适用于任何最新的 JSP 服务器:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
    
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
            <title>Add Course</title>
        </head>
        
        <body>
            <c:if test="${'post' eq fn:toLowerCase(pageContext.request.method) and param.submit ne null}">
                ${pageContext.request.method}
            </c:if>
            <form method="post">
                Name: <input type="text" name="name" /><br />
                Credits: <input type="text" name="credits" /><br />
                <button type="submit" name="submit">Add</button>
            </form>
        </body>
        
    </html>
    
    • 使用fn标签库比较小写字符串
    • 在字符串周围使用单引号以避免转义
    • 对“等于”和“不等于”使用 el eqne 运算符
    • 使用 el and 布尔运算符
    • 使用el变量param访问请求参数
    • 使用${...} 语法而不是scriptlet 输出值

    【讨论】:

    • 我刚刚在 Tomcat 9.0.46 / AdoptOpenJDK 15.0.2.7-hotspot 上进行了测试。两者都有效(因为它们都显示表单,并在您提交后在顶部打印“POST”)。我认为问题不在于您认为的问题...
    猜你喜欢
    • 2012-01-05
    • 2014-12-23
    • 2016-03-17
    • 2012-07-16
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2014-11-11
    相关资源
    最近更新 更多