0

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>
Ahatius
  • 4,777
  • 11
  • 49
  • 79
  • So if its never empty, what's the value? Try printing it and see what it is. – developerwjk Sep 25 '13 at 17:02
  • If you're using AJAX it might also be that the browser is caching the response. Having your JSP print the value of the parameter rather than just say 'not empty' will help you determine that. – developerwjk Sep 25 '13 at 17:13
  • I tried printing it out already, even between quotation marks - it's just nothing. – Ahatius Sep 25 '13 at 17:17

2 Answers2

1

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.

Tomek Rękawek
  • 9,204
  • 2
  • 27
  • 43
0

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

if(authorMail != null && !authorMail.isEmpty()) {
    stmt += "AND s.[cq:lastModifiedBy] = '" + authorMail + "'";
}
Ahatius
  • 4,777
  • 11
  • 49
  • 79