Hey,
I want to print out the contents of a backing bean in an auto-generated way. So all the contents appear on a JSP. Is this possible anyhow?
Thanks in advance, Daniel
Hey,
I want to print out the contents of a backing bean in an auto-generated way. So all the contents appear on a JSP. Is this possible anyhow?
Thanks in advance, Daniel
One way to do this would be using the JavaBean API and a custom tag function.
WEB-INF/tld/beans.tld:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<description>Bean inspector.</description>
<display-name>Bean inspector utils</display-name>
<tlib-version>1.2</tlib-version>
<short-name>beans</short-name>
<uri>http://acme.demo</uri>
<function>
<name>inspect</name>
<function-class>props.Inspector</function-class>
<function-signature>
java.util.List inspect(java.lang.Object)
</function-signature>
</function>
</taglib>
Implementation:
public class Inspector {
public static List<Map.Entry<String, Object>> inspect(
Object bean) {
Map<String, Object> props = new LinkedHashMap<String, Object>();
try {
BeanInfo info = Introspector.getBeanInfo(bean
.getClass(), Object.class);
for (PropertyDescriptor propertyDesc : info
.getPropertyDescriptors()) {
String name = propertyDesc.getDisplayName();
Method reader = propertyDesc.getReadMethod();
Object value = reader.invoke(bean);
props.put(name, value == null ? "" : value);
}
} catch (IntrospectionException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return new ArrayList<Map.Entry<String, Object>>(props
.entrySet());
}
}
This tag library is then imported in the JSP header:
<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core" xmlns:beans="http://acme.demo">
Sample dataTable using the function:
<h:dataTable border="1" value="#{beans:inspect(demoPropsBean)}" var="entry">
<h:column id="column1">
<f:facet name="header">
<h:outputText value="property" />
</f:facet>
<h:outputText value="#{entry.key}" />
</h:column>
<h:column id="column2">
<f:facet name="header">
<h:outputText value="value" />
</f:facet>
<h:outputText value="#{entry.value}" />
</h:column>
</h:dataTable>
See the JavaBean spec for info on how to provide localized property names, etc.