【问题标题】:How to mapping a value to a text?如何将值映射到文本?
【发布时间】:2012-08-29 06:46:07
【问题描述】:

我从数据库查询并收到一个整数列表。例如:0、1、2
如果我在浏览器中显示数字,用户将无法理解数字的含义。
所以,我想将一个数字映射到一个字符串。
例如:0:待处理,1:有效,2:无效,依此类推。
文件 display.xhtml 的源代码如下:

<!--display.xhtml-->
<t:dataTable id="itemTable" value="#{itemBrowser.itemList}" var="item">
  <t:column>
    <f:facet name="header">
      <h:outputText value="Status" />
    </f:facet>
    <h:outputText value="#{itemStatusListReversedString[item.status]}" />
  </t:column>         
</t:dataTable>  

<!--faces-config.xml-->
<managed-bean>
  <managed-bean-name>itemStatusListReversedString</managed-bean-name>
  <managed-bean-class>java.util.HashMap</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
  <map-entries>
    <key-class>java.lang.String</key-class>
    <map-entry>
      <key>0</key>
      <value>Inactive</value>
    </map-entry>
    <map-entry>
      <key>1</key>
      <value>Active</value>
    </map-entry>
    <map-entry>
      <key>2</key>
      <value>Pending</value>
    </map-entry>
  </map-entries>
</managed-bean> 

但是,在浏览器中没有任何输出。那么,我该如何解决这个问题呢?

谢谢

【问题讨论】:

  • 字符串值Pending、Active、Inactive在哪里?它们在数据库中吗?
  • 字符串值是一个数字的含义。它们不存储在数据库中。我只是用它来向用户显示含义。

标签: java jsf jsf-1.2


【解决方案1】:

我认为问题出在这一行:

<h:outputText value="#{itemStatusListReversedString[item.status]}" />

你必须这样做

<h:outputText value="#{item.stringValue}" />

并在 item 类中添加如下内容:

public String getStringValue(){
 return itemStatusListReversedString.get(this.numberValue);
}

您必须更改之前在 faces-config 中的 item 类以注入 itemStatusListReversedString

例子:

itemBrowser.itemList 是 MyClass 的一个对象的 List:

public class MyClass{
//The necessary stuff
private Integer valueFromDB; //0, 1, 2...
private Map<Integer, String> itemStatusListReversedString; //The map you configured in the faces-config.xml

//More stuff

public String getStringValue(){
 return itemStatusListReversedString.get(this.valueFromDB);
}

}

在 faces-config.xml 中你可以这样配置 MyClass:

<bean id="myClassInstance"              
class="package.MyClass" scope="request">    
        <property name="itemStatusListReversedString" ref="itemStatusListReversedString"></property>
    </bean>

当创建 MyClass 的新实例时,使用这种方法而不是使用 new MyClass() 创建它们:

WebApplicationContext webApplicationContext = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        MyClass bean = (MyClass)webApplicationContext.getBean("myClassInstance");

【讨论】:

  • 嗨,Averroes,请解释更多细节。 item 类中的 itemStatusListReversedString 是什么?
【解决方案2】:

使用 enum 然后使用 ordinal() 处理数字,使用 values() 处理文本,例如:

YourEnum.values()[ordinal]

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2021-04-12
    • 2016-07-02
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多