Java JSTL:检查字符串是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23720767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:52:08  来源:igfitidea点击:

JSTL: check if a string is empty

javajspjstl

提问by DaanCelie

I'm trying to test in JSTL if a session attribute is empty. However the attribute is empty JSTL sees it as a non-empty attribute.

如果会话属性为空,我正在尝试在 JSTL 中进行测试。然而,该属性为空 JSTL 将其视为非空属性。

This is the hardcode I'm trying to replace with JSTL. This code is working correctly:

这是我试图用 JSTL 替换的硬代码。此代码工作正常:

<% if (request.getAttribute("error") != null) { %>
    <div class="alert alert-danger">
        <strong>Oh snap, something's wrong, maybe the following error could help you out?<br /></strong>
        <%= request.getAttribute("error")%>
    </div>
<% } %>

This is how I replaced it with JSTL. When checked, the error-attribute is not empty, however it is empty.

这就是我用 JSTL 替换它的方式。勾选后,error-attribute 不是空的,而是空的。

<c:if test="${not empty sessionScope.error}">
    <div class="alert alert-danger">
        <strong>Oh snap, something's wrong, maybe the following error could help you out?<br /></strong>
        <c:out value="${sessionScope.error}" />
    </div>
</c:if>

采纳答案by gyanu

Add the JSTL library and declare the core taglib:

添加JSTL库并声明核心标签库:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

The JSTL equivalent of

JSTL 相当于

<% if (request.getAttribute("error") != null) { %>

is

<c:if test="${not empty error}">

回答by Braj

I'm trying to test in JSTL if a session attributeis empty

如果 asession attribute为空,我正在尝试在 JSTL 中进行测试

You have to check in session scopenot in request scope.

您必须检查会话范围而不是请求范围

It should be

它应该是

<c:if test="${not empty sessionScope.error}">

instead of

代替

<c:if test="${not empty requestScope.error}">


If you are not sure about the scope then use without scope that will look in all scope from bottom to top (page, request, session then finally in application)

如果您不确定范围,则使用不使用范围,从下到上查看所有范围(页面、请求、会话,最后在应用程序中)

<c:if test="${not empty error}">