1

我正在尝试创建一种方法,该方法允许我通过带有 inputText 字段的 JSF 页面进行搜索。我打算从位于托管 bean 中的数组列表中获取一个或多个条目,并在我点击提交后将其显示在 JSF 页面上。我试图从这个问题中汲取灵感,但由于我是 Java 的新手,我一直坚持创建搜索方法: JSF2 搜索框

在我的 JSF 页面中,我打算有这样的东西,“某物”是我缺少的方法:

<h:form>
    <h:inputText id="search" value="#{order.something}">
        <f:ajax execute="search" render="output" event="blur" />
    </h:inputText>
    <h2>
        <h:outputText id="output" value="#{order.something}" />
    </h2>
</h:form>

在我的 java 文件中,我有以下 arraylist 'orderList',我只使用字符串:

private static final ArrayList<Order> orderList = 
    new ArrayList<Order>(Arrays.asList(
    new Order("First", "Table", "description here"),
    new Order("Second", "Chair", "2nd description here"),
    new Order("Third", "Fridge", "3rd description here"),
    new Order("Fourth", "Carpet", "4th description here"),
    new Order("Fifth", "Stuff", "5th description here")
));

希望这是足够的信息。我想我必须从头开始制作一些全新的方法,但我现在没有太多。我将如何将这些捆绑在一起?任何指针将不胜感激:)

〜编辑〜这是我的订单对象供参考,我假设我在这里使用了其中一个吸气剂?

public static class Order{
    String thingNo;
    String thingName;
    String thingInfo;

    public Order(String thingNo, String thingName, String thingInfo) {
        this.thingNo = thingNo;
        this.thingName = thingName;
        this.thingInfo = thingInfo;
    }
    public String getThingNo() {return thingNo;}
    public void setThingNo(String thingNo) {this.thingNo = thingNo;}
    public String getThingName() {return thingName;}
    public void setThingName(String thingName) {this.thingName = thingName;}
    public String getThingInfo() {return thingInfo;}
    public void setThingInfo(String thingInfo) {this.thingInfo = thingInfo;}
    }
4

1 回答 1

2

首先,您需要对 java 相等性做一些工作:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

搜索 ArrayList(可能不是最好的结构,但它确实有效)需要编写一个函数来处理它,在第一个示例中,它使用 commandButton 的操作(执行一个方法)。你所拥有的不会做任何事情,因为它没有任何东西可以执行(没有调用任何方法)。

如果您只是学习 JSF 并且不熟悉 Java,我建议您保持简单,直到您了解生命周期。如果您没有扎实的 Java 背景,那可能会非常令人沮丧。

但是,要回答您的问题,您需要对 ValueChangeEvent 做一些事情,因为您没有命令(根据他的回答的后半部分)。

您的“搜索方法”将是作用于数据结构的纯 Java。一个简单的实现可能是:

  public void searchByFirstValue(String search)
  {
    if(search == null || search.length() == 0)
      return;

    for(Order order : orderList)
    {
      if(order.getFirstValue().contains(search)) //java.lang.String methods via a regular expression
        setSelectedOrder(order);

      return;
    }
  }

这假定您的 Order 对象有一个方法 getFirstValue() 返回一个字符串。我还假设根据您的构造函数 value 永远不会为 null (有很多潜在的陷阱)。假设您已经在 web.xml 中注册了“OrderBean”,或者您使用了 ManagedBean 注释,您的 JSF 可能如下所示:

    <h:form>
    <h:inputText id="search" valueChangeListener="#{orderBean.onChange}"> <!--Use the previous example -->
        <f:ajax execute="search" render="output" event="blur" />
    </h:inputText>
    <h2>
        <h:outputText id="output" value="#{orderBean.order}" /> <!-- this is the object from setSelectedOrder(order); -->
    </h2>
    </h:form>

希望这会为您指明正确的方向。同样,在您了解框架的基础知识之前,我会坚持使用操作/操作侦听器。从那里开始很容易转移到非常复杂的动作,而无需大量工作。我这么说的原因是它们更容易调试并且很容易理解。

于 2012-08-10T02:13:19.940 回答