5

I was wondering if we could check for all undefined and null variables in JSP using its built-in functions?

I know I can build a function to do that, but I need a lazy solution.

Tamás
  • 47,239
  • 12
  • 105
  • 124
cipher
  • 2,414
  • 4
  • 30
  • 54

4 Answers4

7
<c:if test="${name == null}">variable name is undefined</c:if>

For testing you can define and undefine a variable using:

<c:set var="name" value="Petra"/>
<c:set var="name" value="${null}"/>

To state you are using the core JSTL tags add this to the top of the page:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
Jano
  • 62,815
  • 21
  • 164
  • 192
  • Real Problem is: on posting data through forms. Wanted to check null and "" both at a same time. Guess there is nothing left than to write the function myself – cipher Aug 20 '12 at 07:03
  • 1
    you can now (2014) do variable name is undefined – Tim Perry Jul 01 '14 at 18:05
3

There are No built-in functions to check this in a JSP, so I guess you would have to make one, which I think should be a fairly simple task if you take the bookish meaning of null.

If not bookish then null is sort of an overloaded term, it could mean any of the following in general usage:

  1. actually null String, which could throw NullPointerException.
  2. "", empty string which might be called null.
  3. "null"
  4. An acutally null array. :-)
  5. An empty array.
  6. An array with just null objects ...

So you can build a method to include these or other cases you can think of for null-check or just the basic-primitive-unembellished null-check.

In Java I suppose there is no such thing as an undefined variables, since it is a statically typed language and compiler would catch any of these so called undefined errors :-)

In PHP (since I think you took this function from there) you have these things because it is a scripting language and is not a statically typed language like Java.

Hope this helps.

Community
  • 1
  • 1
Prakash K
  • 11,669
  • 6
  • 51
  • 109
0

Instead of checking against null, you can use this snippet:

<c:if test="${not name}">variable name is undefined</c:if>
L.Butz
  • 2,466
  • 25
  • 44
Argh
  • 1
  • 3
0

for checking variable is sent or not use following function

request.getParameterMap().containsKey("variable")

if(request.getParameterMap().containsKey("name"))
{
     out.print(request.getParameter("name"));
}
Nerdroid
  • 13,398
  • 5
  • 58
  • 69
Dhiraj
  • 1
  • 1