Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP bean tag for property that might not exist

In JSP I can reference a bean's property by using the tag ${object.property}

Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example:

public class Person {
    public String getName()
}
public class Employee extends Person {
    public float getSalary()
}

In JSP I want to display a table of people with columns of name and salary. If the person is not an employee then salary should be blank. The row HTML might look like:

<tr>
    <td><c:out value="${person.name}"></td>
    <td><c:out value="${person.salary}"></td>
</tr>

Unfortunately if person is not an employee then it can't find salary and an error occurs. How would I solve this in JSP?

Edit: Is there an instanceof check in JSP tag language?

like image 422
Steve Kuo Avatar asked Oct 31 '08 19:10

Steve Kuo


3 Answers

Just use the EL empty operator IF it was a scoped attribute, unfortunately you'll have to go with surrounding your expression using employee.salary with <c:catch>:

<c:catch var="err">
    <c:out value="${employee.salary}"/>
</c:catch>

If you really need instanceof, you might consider a custom tag.

like image 114
Eric Wendelin Avatar answered Nov 14 '22 13:11

Eric Wendelin


If you want the class, just use ${person.class}. You can also use ${person.class.name eq 'my.package.PersonClass'}

You can also use the "default" on c:out.

 <c:out value='${person.salary}' default="Null Value" />
like image 24
James Schek Avatar answered Nov 14 '22 11:11

James Schek


Concise, but unchecked.

<tr>
    <td>${person.name}</td>    
    <td>${person.class.simpleName == 'Employee' ? person.salary : ''}</td>
</tr>

Is there an instanceof check in JSP tag language?

Not at the moment of this writing. I read somewhere that they have reserved it, instanceof keyword, in EL, may be for future. Moreover, there is a library available that has this specific tag. Look into that before deciding to create some custom tag for yourself. Here is the link, Unstandard Tag Library.

like image 3
Adeel Ansari Avatar answered Nov 14 '22 11:11

Adeel Ansari