Check if parameter exists in Expression Language [duplicate]
Asked Answered
K

3

46
<c:if test="${param.username}" >
</c:if>

How do I check if param.username exists??

Kehr answered 7/6, 2012 at 13:20 Comment(0)
H
75

Use the not empty check.

<c:if test="${not empty param.username}" >
</c:if>

Edit: If you have a parameter of the form ?username (no value), it is safer to use ${param.username ne null}

Hairpin answered 7/6, 2012 at 13:22 Comment(3)
What if host/?parameter. It exists but is empty.Sulfapyridine
I have just tested in my Java EE 6 environment Servlet 3.0 and it DOES NOT work: page/?fail -> does it exists? yes, the parameter exists. ${ not empty param.fail } -> falseSulfapyridine
This answer should not be getting upvoted. "domain.com/login?fail" produces produce a param ("fail") that does exist, but is empty.Ancestor
M
48

If you want to check if parameter exists, just test if it is not null, in your case:

<c:if test="${param.username != null}"></c:if>



Broader explanation:

If you want to check:

  • if yourParam exists/ is not null:

    <c:if test="${param.yourParam != null}"></c:if>

  • if yourParam does not exist/ is null

    <c:if test="${param.yourParam == null}"></c:if>

  • if yourParam is not empty (not empty string and not null)

    <c:if test="${!empty param.yourParam}"></c:if>

  • if yourParam is empty (empty string or null)

    <c:if test="${empty param.yourParam}"></c:if>

  • if yourParam evaluates to 'true'

    <c:if test="${yourParam}"></c:if>

  • if yourParam evaluates to 'false' (string other than 'true')

    <c:if test="${!yourParam}"></c:if>

Melendez answered 14/3, 2014 at 10:30 Comment(1)
Nice answer showing all possible options and how they operate.Deceit
B
6

If I may add a comment...

To test if the request parameter "username" does not exist in the JSP page "a-jsp.jsp", we can write an "if" clause in the page "a-jsp.jsp":

<c:if test="${empty param['username']>
...
</c:if>

We'll go through that "if" clause if the requested URL is:

http://server/webapp/a-jsp.jsp

or

http://server/webapp/a-jsp.jsp?username=

We won't if the requested URL is:

http://server/webapp/a-jsp.jsp?username=foo

Beadle answered 24/9, 2013 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.