How can I validate if a String
is null or empty using the c
tags of JSTL
?
I have a variable of name var1
and I can display it, but I want to add a comparator to validate it.
<c:out value="${var1}" />
I want to validate when it is null or empty (my values are strings).
This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.
To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :
<%@ 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>
to also check blank string, I suggest following
<%@ 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>
It also handles nulls
if you check only null or empty then you can use the with default option for this:
<c:out default="var1 is empty or null." value="${var1}"/>
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 }">
<a href="javascript:void(0);">Change Design</a>
</c:if>
You can use
${var == null}
alternatively.
Here's an example of how to validate a int and a String that you pass from the Java Controller to the JSP file.
MainController.java:
@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
<%@ 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>
Here's the one liner.
${empty value?'value is empty or null':'value is NOT empty or null'}
Source: Stackoverflow.com