Question

I've got this simple piece of code in my JSP for my CQ5 page, but I can't get it to work properly. I'd like to check if one of the input fields is beeing sent empty but it always outputs "not empty":

<%
if(slingRequest.getParameter("authorMail") == null) {
    %>empty<%
} else {
    %>not empty<%
}
%>

I've tried validating against "null", "" and " " but none of those will ever get my condition to output "empty". It only works if I remove the input field completly from my form.

I could work out something on the frontend with jQuery, but I think it's kinda stupid for something as simple as this. Does anyone know how to check a GET parameter is actually empty?

This is the whole JSP:

<%@include file="/libs/foundation/global.jsp"%>
<html>
<head>
    <title>Test</title>
</head>

<body>
    <form method="get" action="<%= currentPage.getPath() %>.html">
        <input type="text" name="authorMail" id="authorMail" />
        <input type="submit" />
    </form>

    <%
    if(slingRequest.getParameter("authorMail") == "") {
        %>empty<%
    } else {
        %>not empty<%
    }
%>

___
"<%=slingRequest.getParameter("authorMail")%>"
___
</body>
</html>
Was it helpful?

Solution

You can't compare two strings using ==, as this operator compares objects reference rather than object content. Use equals() method to compare strings.

That's why you need to first use authorEmail != null to check if the parameter is present (it will be after submitting form) and then !authorEmail.isEmpty() to check if the string is not empty. The second method is the same as !authorEmail.equals("").

You may also use handy StringUtils.isNotEmpty() method.

OTHER TIPS

For some reason using the following condition works without a problem:

if(authorMail != null && !authorMail.isEmpty()) {
    stmt += "AND s.[cq:lastModifiedBy] = '" + authorMail + "'";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top