当前位置: 代码迷 >> java >> 如何在jsf中停止表行重复?
  详细解决方案

如何在jsf中停止表行重复?

热度:56   发布时间:2023-07-17 21:05:29.0

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

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

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

list = new ArrayList();

您可以使用Set而不是List 如果您担心订单,可以使用SortedSet Set不允许对象被添加到它,如果已经有一个等于它的Set

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

setTable(new UISheet()); //binding set to table attribute
if (data == null) {
// do something with data
} return data;
  相关解决方案