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).
You can use the
empty
keyword in a<c:if>
for this:Or the
<c:choose>
:Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator
${condition? valueIfTrue : valueIfFalse}
:To learn more about those
${}
things (the Expression Language, which is a separate subject from JSTL), check here.See also:
Here's the one liner.
Ternary operator inside EL
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:
importJavaToJSPExamples.jsp
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}"/>
to also check blank string, I suggest following
It also handles nulls