2009-05-06 18 views

回答

1

的一种方式。

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

样品的dataTable使用功能:

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

+0

感谢您的回答! 我试过了,并且出现错误: javax.servlet.ServletException:调用函数'beans:inspect'时出现java.lang.NullPointerException的根本原因时出现问题。 也许我传递了一个错误的参数。 这是错误的吗? – 2009-05-06 16:44:25