save the changes from JSP table into the database

时间:2017-12-18 08:15:13

标签: java mysql sql jsp

I have a table which displays the content of a database. I want to save the changes edited in the table to my database. The problem is no matter what row I edit, each time when I try to save, it takes as parameters the values from the first row.

Main.jsp:

unset($columns['status'])

update.jsp:

<FORM NAME="form1" METHOD="POST" action="update.jsp">
    <table>
        <% ResultSet rs=statement.executeQuery(query);
        while(rs.next())
        {%>
            <tr>
                <td style="display:none;"><input type="text" name="id" value="
                <%=rs.getInt("ID") %>"></td>
                <td><input type="text" name="val1" value="<%=rs.getString("Value1") %>"></td>
                <td><input type="text" name="val2" value="<%=rs.getString("Value2") %>"></td>
                <td><input type="submit" name="Submit" value="Save"></td>
            </tr>
        <% } %>
    </table>
</FORM> 

1 个答案:

答案 0 :(得分:1)

由于Main.jsp中的所有行都具有相同的名称(idval1val2),因此每当您进行request.getParamater()来电时,将返回第一个匹配参数。

您可以通过获取所有参数值来解决此问题。

String[] ids = request.getParameterValues("id");

您必须相应地修改Main.jsp,以确保在update.jsp

中获取正确的值组合

但是,由于您只想提交点击Save的行,因此您可以在行上声明Form,而不是拥有全局Form

<!--FORM NAME="form1" METHOD="POST" action="update.jsp"-->
    <table>
        <% ResultSet rs=statement.executeQuery(query);
        while(rs.next())
        {%>
            <tr>
                <td style="display:none;">
                <FORM NAME="form1" METHOD="POST" action="update.jsp">
                <input type="text" name="id" value="
                <%=rs.getInt("ID") %>"></td>
                <td><input type="text" name="val1" value="<%=rs.getString("Value1") %>"></td>
                <td><input type="text" name="val2" value="<%=rs.getString("Value2") %>"></td>
                <td><input type="submit" name="Submit" value="Save"></FORM></td>
            </tr>
        <% } %>
    </table>
<!--/FORM-->