Evaluate empty or null JSTL c tags
如何使用
我有一个名为
1 | <c:out value="${var1}" /> |
我想验证它是null还是空(我的值是字符串)。
How can I validate if a String is null or empty using the c tags of JSTL?
您可以在
1 2 3 4 5 6 | <c:if test="${empty var1}"> var1 is empty or null. </c:if> <c:if test="${not empty var1}"> var1 is NOT empty or null. </c:if> |
或者
1 2 3 4 5 6 7 8 | <c:choose> <c:when test="${empty var1}"> var1 is empty or null. </c:when> <c:otherwise> var1 is NOT empty or null. </c:otherwise> </c:choose> |
或者,如果您不需要有条件地渲染一堆标记,因此您只能在标记属性中检查它,那么您可以使用EL条件运算符
1 | <c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" /> |
要了解有关
也可以看看:
- EL空运算符如何在JSF中工作?
还要检查空白字符串,我建议如下
1 2 3 4 5 6 | <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:if test="${empty fn:trim(var1)}"> </c:if> |
它还处理空值
如果只检查null或为空,则可以使用with default选项:
这是一个班轮。
EL内部的三元运算符
1 | ${empty value?'value is empty or null':'value is NOT empty or null'} |
此代码是正确的,但如果您输入了大量空格('')而不是null或空字符串
返回false。
要更正此问题,请使用常规表达式(下面的代码检查变量是null还是空或空白与org.apache.commons.lang.StringUtils.isNotBlank相同):
1 2 3 4 5 6 7 | <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <c:if test="${not empty description}"> <c:set var="description" value="${fn:replace(description, ' ', '')}" /> <c:if test="${not empty description}"> The description is not blank. </c:if> </c:if> |
您可以使用
1 | ${var == null} |
或者。
这是一个如何验证从Java控制器传递到JSP文件的int和String的示例。
MainController.java:
1 2 3 4 5 6 7 8 9 10 11 | @RequestMapping(value="/ImportJavaToJSP") public ModelAndView getImportJavaToJSP() { ModelAndView model2= new ModelAndView("importJavaToJSPExamples"); int someNumberValue=6; String someStringValue="abcdefg"; //model2.addObject("someNumber", someNumberValue); model2.addObject("someString", someStringValue); return model2; } |
importJavaToJSPExamples.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <p> ${someNumber} </p> <c:if test="${not empty someNumber}"> <p> someNumber is Not Empty </p> </c:if> <c:if test="${empty someNumber}"> <p> someNumber is Empty </p> </c:if> <p> ${someString} </p> <c:if test="${not empty someString}"> <p> someString is Not Empty </p> </c:if> <c:if test="${empty someString}"> <p> someString is Empty </p> </c:if> |
1 2 3 4 5 6 7 8 9 | In this step I have Set the variable first: <c:set var="structureId" value="<%=article.getStructureId()%>" scope="request"></c:set> In this step I have checked the variable empty or not: <c:if test="${not empty structureId }"> Change Design </c:if> |