How to detect bean property in JSTL?
I need detect java bean property inside JSP page. I didn’t found any way how to solve
this problem in JSTL or more precisely through expression language. In some cases view
code iterates over returned model (java beans) , but doesn’t know which kind of bean is
in model. It would be for example bean represents Car or House and every one has various
properties to be displayed.
Consider this example:
We iterate over collection of model data and write price information to output. But it is possible that this instance of model hasn’t property price and code ${foo.price} causes exception. I don’t really know how to detect if bean has some property through expression language and therefore i made simply tag for this purpose (detect property on bean). This tag use reflection to determine if bean has appropriate property.
protected int doStartTagInternal() throws Exception {
.
.
.
Field field[] = bean.getClass().getDeclaredFields();
for (int i = 0; i < field.length; i++) {
if(prop.equals(field[i].getName())){
pageContext.setAttribute("hasProperty", prop);
break;
}
}
return SKIP_BODY;
}Simply modification of prevous example:
I would like to notice that maybe would be better to define a function (by the help of JSP expression language) that can be invoked in an expression.
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio