如何停止 jsf 中的 table 行重复?

How to stop table row duplications in jsf?

我正在开发一个带有 primefaces 的 jsf 应用程序。在应用程序中我有几个 tables。但是,每当我刷新页面或向 table 添加新值或重新访问该页面时,table 中的值就会重复。现在我知道是什么原因造成的。在我的支持 bean 中,我在每个函数中使用驱动程序管理器获取连接来建立数据库连接,然后在函数完成时关闭数据库连接。但是,当我刷新页面时,显然会再次调用获取数据函数并将值附加到 table。我也知道数据库池是这里最好的解决方案,但我无法让它与我的应用程序一起使用。我的问题是如何防止 jsf/primefaces table 中的行重复并保持数据库连接以便我可以从数据库中检索这些值?下面是 Animal Bean class,它具有添加动物的功能和从数据库中检索所有动物的功能。 注意:数据库 table 中没有重复项,只是在 jsf 视图或 jsf table

@ManagedBean(name = "animal")
@ViewScoped
public class Animal {

    public String id;
    public String breed;
    public String gender;
    public double age;
    public double weight;
    public String description;
    public String herd;
    public DataSource dataSource;
    public Connection DBConn;
    public ArrayList list = new ArrayList();

    public Animal() {



    }

    public Animal(String id, String breed, double weight, double age, String gender, String description) {
        this.id = id;
        this.breed = breed;
        this.weight = weight;
        this.age = age;
        this.gender = gender;
        this.description = description;
    }

    /**
     * Creates a new instance of herd
     *
     * @return
     */
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public double getAge() {
        return age;
    }

    public void setAge(double age) {
        this.age = age;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getHerd() {
        return herd;
    }

    public void setHerd(String herd) {
        this.herd = herd;
    }

    public String addAnimal() throws SQLException {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        int insert = 0;

        FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        PreparedStatement ps = null;

        try {

            if (DBConn != null) {
                String sql = "INSERT INTO animal(animalsTag,breed,age,weight,description,gender,farmid)VALUES(?,?,?,?,?,?,?)";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ps.setString(1, id);
                ps.setString(2, breed);
                ps.setDouble(3, age);
                ps.setDouble(4,weight);
                ps.setString(5, description);
                ps.setString(6, gender);
                ps.setInt(7, value);
                insert = ps.executeUpdate();
                System.out.println(insert);
                System.out.println("Data Added Successfully");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();



            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (insert > 0) {
            return "yes";
        } else {
            return "no";
        }

    }

    public ArrayList<Animal> allAnimals() {

         try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        PreparedStatement ps = null;

         FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        try {

            if (DBConn != null) {
                String sql = "Select animalsTag,breed,age,weight,description,gender FROM animal where farmid = '"
                            + value + "'";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();

                if (!rs.next()) {

                    return null;
                } else {

                    rs.beforeFirst();

                    while (rs.next()) {

                        Animal animal = new Animal(
                                rs.getString("animalsTag"),
                                rs.getString("breed"),
                                rs.getDouble("age"),
                                rs.getDouble("weight"),
                                rs.getString("description"),
                                rs.getString("gender"));

                        list.add(animal);

                    }//end while

                }

            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }


}

JSF 代码

 <p:layout fullPage="true">

            <p:layoutUnit position="north" size="100" resizable="true" closable="true" collapsible="true">
                <div id="banner" style="float:right;">
                     <p:commandButton value="Log Out" action="#{farm.logout()}" />     
                </div>
             <p:graphicImage url="/resources/images/Demeter1.png" />
            </p:layoutUnit>

            <p:layoutUnit position="south" size="100" closable="true" collapsible="true">
                Footer
            </p:layoutUnit>

            <p:layoutUnit position="west" size="175" header="Left" collapsible="true">
                <p:menu>
                    <p:submenu label="Index">
                        <p:menuitem value="Manage Farm" url="managefarm.xhtml"/>
                        <p:menuitem value="Add Paddock" url="outline.xhtml"/>
                        <p:menuitem value="Create Grass Wedge" url="grass.xhtml"/>
                        <p:menuitem value="Herd Management" url="addAnimal.xhtml"/>

                    </p:submenu>

                </p:menu>
            </p:layoutUnit>

            <p:layoutUnit position="center">
                <h1>You can see all animals on your farm here.</h1>


                <p:dataTable var="animal" value="#{animal.allAnimals()}">
                    <p:column headerText="Id">
                        <h:outputText value="#{animal.id}" />
                    </p:column>

                    <p:column headerText="Age">
                        <h:outputText value="#{animal.age}" />
                    </p:column>

                    <p:column headerText="Breed">
                        <h:outputText value="#{animal.breed}" />
                    </p:column>

                    <p:column headerText="Weight">
                        <h:outputText value="#{animal.weight}" />
                    </p:column>
                </p:dataTable>



            </p:layoutUnit>

        </p:layout>

您可以使用 Set 而不是 List。如果您担心订单,您可以使用 SortedSet。如果 Set.

中已经有一个对象与之相等,则 Set 不允许向其添加对象

您的 bean 是 Viewscoped,这意味着当您停留在页面上时,bean 包含的数据仍然有效。为什么这有关系 ?因为您的动物列表仍然包含您之前添加的内容以及您在方法 allAnimals() 中添加的内容。换句话说,将其添加到方法 allAnimals().

的第一行
list = new ArrayList();

Ced 关于将组件设置为新对象的回答对我有用。我使用 MyFaces Apache Tobago 作为组件框架,我必须在方法顶部设置一个新的 UISheet() 来检索特定 table 的数据值。例如table 的值属性绑定到什么。这很棒,因为我不需要担心为这些分离视图范围:-)。

setTable(new UISheet()); //binding set to table attribute
if (data == null) {
// do something with data
} return data;