Struts2, String null check

49,469

Solution 1

Try it without the #.

 <s:if test="%{col==null}">0</s:if>

I think the has will attempt to resolve 'col' first, and use the value of col as the property name. Since that'd be empty, it'd do a comparison of "" as the property name, which is the top of the value stack. I'm not sure how that would evaluate here.

I always use something like this:

<s:if test="%{licenseStatusString != null}">
 ... something that uses licenseStatusString
</s:if>

Solution 2

It depends whether you're using Struts2.0.x or a higher version, as id attribute has been replaced for var attribute in s:iterator since Struts2.1.x.

Asuming Struts 2.1.x, the best way is to assign var attribute and use it as a variable (as you already suggested)

<s:iterator value="bar" var="foo">
    <s:if test="#foo==null || #foo==''">0</s:if>
</s:iterator>

You may also want to use top variable to get top stack value, but it may enter in conflict with your objects attributes. Still it works

<s:iterator value="bar">
    <s:if test="top==null || top==''">0</s:if>
</s:iterator>

But, if you only need to print String's result, with no conditions, whether it is null or empty, just do it as simple as this

<s:iterator value="bar">
    <s:property /> <!-- prints iterator current value or '' if its null -->
</s:iterator>

Ps. It's not necessary to use ognl markup %{} inside the test attribute of a s:if, or the value attribute of a s:property.

For more examples check struts2 iterator doc

Solution 3

You can do it in one line ( single if statement):

<s:property value="%{col==null ? '0':col}"/></s:else>

Or add more string

<s:property value="%{col==null ? '0': 'The column is' + col}"/></s:else>
Share:
49,469
Farmor
Author by

Farmor

Updated on April 25, 2020

Comments

  • Farmor
    Farmor about 4 years

    I'm trying to do a null check on a String but it won't work.

    <s:iterator value="matrix" var="row">
        <tr>
           <s:iterator value="value" var="col">
                <td>    
                    <s:if test="%{#col==null}">0</s:if>
                    <s:else><s:property value="col"/></s:else>
                </td>
            </s:iterator>
        </tr>
    </s:iterator>
    

    matrix is a

    Map<Integer, List<String>>
    

    The var "col" is correctly assigned a String value from the List.
    The list may look like this [ "hello" , null , "world ]

    Current output: hello world
    Wanted output: hello 0 world

    /Thanks in advance