2

我想以自动生成的方式打印出支持 bean 的内容。所以所有的内容都出现在一个 JSP 上。这有可能吗?

在此先感谢,丹尼尔

4

1 回答 1

1

一种方法是使用JavaBean API自定义标记函数

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>

执行:

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());
  }
}

然后将此标记库导入 JSP 标头中:

<?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">

使用函数的示例数据表:

<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>

有关如何提供本地化属性名称等的信息,请参阅JavaBean 规范。

于 2009-05-06T11:07:41.167 回答