0

大家好,我有一个来自 primefaces 库的数据表,我试图包含编辑每个单元格的功能,当用户按下行上的“保存”按钮时,它会将编辑后的值更新到数据库,但是目前当用户编辑一个单元格,无论他们将单元格更改为第二个他们单击单元格时的值与以前的值相同,它不会保存新值,另一个问题是当用户最后按下保存时传递给数据库的值始终为空,我该如何解决这两个问题?

这是xhtml

<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"  
                                 paginator="true" rows="10"  

                                 paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"  
                                 rowsPerPageTemplate="5,10,15,25"
                                 editable="true" editMode="cell"
                                 >  
                        <p:column>
                            <!--
                            <p:ajax event="rowEdit" listener="{u.onEdit}" update=":form:messages" />  
                            <p:ajax event="rowEditCancel" listener="{u.onCancel}" update=":form:messages" />  
                            -->

                            <f:facet name="header">
                                User ID
                            </f:facet>
                            #{u.userID}
                        </p:column>

                        <p:column headerText="Name" >
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{u.name}" />
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText id="NameInput" value="#{u.name}"
                                                 style="width:96%" />
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column headerText="Email">
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{u.email}" />
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText id="EmailInput" value="#{u.email}"
                                                 />
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column headerText="Address">
                            <p:cellEditor>
                                <f:facet name="output">
                                    <h:outputText value="#{u.address}" />
                                </f:facet>
                                <f:facet name="input">
                                    <p:inputText id="AddressInput" value="#{u.address}"
                                                 />
                                </f:facet>
                            </p:cellEditor>
                        </p:column>

                        <p:column>
                            <f:facet name="header">
                                Created Date
                            </f:facet>
                            #{u.created_date}
                        </p:column>

                        <p:column>
                            <f:facet name="header">
                                Delete
                            </f:facet>
                            <h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
                        </p:column>

                        <p:column>
                            <f:facet name="header">
                                Save Edit
                            </f:facet>
                            <h:commandButton value="Save" action="#{user.editData(u.userID)}" />
                        </p:column>
                    </p:dataTable>

这是支持 bean,尽管目前这只是使用数据包中的值更新数据库

public void editData(long userID) {
        System.out.println(name);
        PreparedStatement ps = null;
        Connection con = null;
        if (userID != 0) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                System.out.println(name);
                String sql = "UPDATE user1 set name = '" + name + "', email = '" + email + "', address = '" + address + "' WHERE userId=" + userID;
                ps = con.prepareStatement(sql);
                int i = ps.executeUpdate();
                if (i > 0) {
                    System.out.println("Row updated successfully");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    con.close();
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

数据表最初从数据库中获取其值

谢谢

这是我使用数据库中的值填充数据表的方法,/*

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import richard.test.User;

@ManagedBean(name = "userBean")
@SessionScoped
public class UserBean {

    List<User> list;
    PreparedStatement ps = null;
    Connection con = null;
    ResultSet rs = null;

    public List<User> getList() {
        return list;
    }

    public List<User> getUserList() {
        list = new ArrayList<User>();

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            String sql = "select * from user1";
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                User usr = new User();
                usr.setUserID(rs.getLong("userId"));
                usr.setName(rs.getString("name"));
                usr.setEmail(rs.getString("email"));
                usr.setAddress(rs.getString("address"));
                usr.setCreated_date(rs.getDate("created_date"));
                list.add(usr);
                Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
                List<User> checkedItems = new ArrayList<User>();
                for (User item : list) {
                    if (checked.get(item.getUserID()) != null) {
                        checkedItems.add(item);
                        usr.delete(usr.getUserID());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
                ps.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}

这是完整的用户 bean 代码

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.test;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIColumn;
import javax.faces.event.ActionEvent;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;

@ManagedBean
@RequestScoped
public class User {

    List<User> list;
    PreparedStatement ps = null;
    Connection con = null;
    ResultSet rs = null;
    private long userID = 1;
    private String name;
    private String address;
    private Date created_date;
    private String email;
    boolean editable;

    public boolean isEditable() {
        return editable;
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
    }

    public String editAction(User order) {
        order.setEditable(true);
        return null;
    }

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getCreated_date() {
        return created_date;
    }

    public void setCreated_date(Date created_date) {
        this.created_date = created_date;
    }

    public String add() {

        System.out.println("In add");
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        int i = 0;

        if (userID != 0) {
            PreparedStatement ps = null;
            Connection con = null;
            try {
                System.out.println("about to add to db");
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                String sql = "INSERT INTO user1( name, email, address, created_date) VALUES(?,?,?,?)";
                ps = con.prepareStatement(sql);
                ps.setString(1, name);
                ps.setString(2, email);
                ps.setString(3, address);
                if (created_date != null) {
                    String date = fmt.format(created_date);
                    Object obj = date;
                    if (obj == null) {
                        ps.setDate(4, null);
                    } else {
                        java.sql.Date dt = java.sql.Date.valueOf(new String(date));
                        ps.setDate(4, dt);
                    }
                }

                i = ps.executeUpdate();
                System.out.println("Data Added Successfully");

            } catch (Exception e) {
                System.out.println(e);
            } finally {
                try {
                    con.close();
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (i > 0) {
                return "output";
            } else {
                return "invalid";
            }
        } else {
            return "invalid";
        }
    }

    public void delete(long userID) {
        PreparedStatement ps = null;
        Connection con = null;
        if (userID != 0) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                String sql = "DELETE FROM user1 WHERE userId=" + userID;
                ps = con.prepareStatement(sql);
                int i = ps.executeUpdate();
                if (i > 0) {
                    System.out.println("Row deleted successfully");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    con.close();
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }



    public void editData(long userID) {
        PreparedStatement ps = null;
        Connection con = null;
        if (userID != 0) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                System.out.println(name);
                String sql = "UPDATE user1 set name = '" + name + "', email = '" + email + "', address = '" + address + "' WHERE userId=" + userID;
                ps = con.prepareStatement(sql);
                int i = ps.executeUpdate();
                if (i > 0) {
                    System.out.println("Row updated successfully");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    con.close();
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
4

1 回答 1

1

主要问题是您有两个 User 对象:

  • 用户u - 当前选择的用户。
  • 用户用户- 只是一个 ManagedBean,很可能没有状态(没有 id、没有名字、没有地址)。

在执行编辑操作时,您尝试使用u.iduser.nameuser.address等。您需要做的是从u对象中获取所有值。

有许多不同的方法(我从未使用过第三种方法,但它应该可以工作,并且它最接近您已有的方法):

A1。您可以将当前选定的对象保留在 UserBean 中并使用 setPropertyActionListener 进行设置:

<f:setPropertyActionListener target="#{userBean.selectedUser}" value="#{u}" />

然后您可以调用在同一个 bean 中实现的编辑方法(它可以完全访问 selectedUser 对象,并且它可以实现编辑本身,只需将操作委托给具有编辑方法实现的对象)。

A2。您可以将编辑方法放在 UserBean 中并将整个 User 对象作为参数传递:

<h:commandButton value="Save" action="#{userBean.editData(u)}" />

A3。或者你可以打电话:

<h:commandButton value="Save" action="#{u.editData()}" />

代替:

<h:commandButton value="Save" action="#{user.editData(u.userID)}" />
于 2013-10-27T21:10:40.000 回答