如何用JSP将单选框、复选框值存入数据库?提交更新功能求助
Hey Fernando, let's tackle your problem with updating the database when users submit feedback on tweet results. I'll break this down into fixing your current code, implementing the update logic, and explaining how to handle radio/checkbox values in JSP.
1. Fix Your Existing JSP Markup First
Your current code has a few structural issues that need fixing before we get to the database update part:
- Duplicate
<tr>tags for the table header, which breaks the table layout - Form structure that wraps only part of the table row, leading to invalid HTML
- An undefined
refreshpage()function in theonsubmithandler that blocks form submission entirely
Here's the cleaned-up, functional version of your tweet list table:
<table class="display dataTable no-footer" id="DataTables_Table_0"> <tr> <td><b>tweet</b></td> <td><b>retweet</b></td> <td><b>usuario</b></td> <td><b>Geolocalización</b></td> <td><b>creador</b></td> <td><b>¿Relevante?</b></td> <td><b>Tipo de Delito</b></td> <td>Acción</td> </tr> <% Class.forName("com.mysql.jdbc.Driver"); Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "test", "test"); // Use PreparedStatement to avoid SQL injection risks String query = "select * from cataluna_sin;"; PreparedStatement statement = connect.prepareStatement(query); ResultSet rs = statement.executeQuery(); while (rs.next()) { long tweetId = rs.getLong("id"); %> <tr> <td><%= new String(rs.getString("tweet").getBytes("ISO-8859-1"), "UTF-8") %></td> <td><%= rs.getInt("retweets") %></td> <td><%= rs.getString("usuario") %></td> <td><%= rs.getString("geolocalizacion") %></td> <td><%= rs.getString("creador") %></td> <td> <form action="Update.jsp" method="post"> <!-- Hidden field to pass the unique tweet ID to the update handler --> <input type="hidden" name="tweetId" value="<%= tweetId %>"> <!-- Radio buttons for relevance feedback --> <input type="radio" value="No" name="relevante" checked>No<br> <input type="radio" value="Si" name="relevante">Si<br> <!-- Optional: Checkboxes for category selection (adjust values to your needs) --> <div style="margin-top:8px;"> <label><input type="checkbox" name="dominio[]" value="Deportes"> Deportes</label> <label><input type="checkbox" name="dominio[]" value="Compras"> Compras</label> <label><input type="checkbox" name="dominio[]" value="Informática"> Informática</label> </div> <input type="submit" value="clasificar" style="margin-top:8px;"> </form> </td> <td></td> </tr> <% } // Close database resources to prevent leaks rs.close(); statement.close(); connect.close(); %> </table>
2. Implement the Database Update Logic (Update.jsp)
Create a separate Update.jsp file to handle form submissions and update the database. This separates presentation from business logic, making your code easier to maintain.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.sql.*" %> <% // Retrieve form parameters long tweetId = Long.parseLong(request.getParameter("tweetId")); String relevante = request.getParameter("relevante"); // Handle multiple checkbox selections String[] dominios = request.getParameterValues("dominio[]"); String dominioStr = dominios != null ? String.join(", ", dominios) : ""; Connection connect = null; PreparedStatement pstmt = null; try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "test", "test"); // Update query - adjust column names to match your table schema String updateQuery = "UPDATE cataluna_sin SET relevante = ?, dominio = ? WHERE id = ?"; pstmt = connect.prepareStatement(updateQuery); pstmt.setString(1, relevante); pstmt.setString(2, dominioStr); pstmt.setLong(3, tweetId); int rowsUpdated = pstmt.executeUpdate(); if (rowsUpdated > 0) { out.println("¡Feedback enviado exitosamente!"); // Redirect back to the tweet list after 2 seconds response.setHeader("Refresh", "2; URL=tweetList.jsp"); // Replace with your list page name } else { out.println("Error al actualizar el feedback."); } } catch (Exception e) { out.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { // Always close resources in a finally block to avoid leaks try { if (pstmt != null) pstmt.close(); } catch (Exception e) {} try { if (connect != null) connect.close(); } catch (Exception e) {} } %>
3. Key Concepts Explained
- Hidden Field: The
tweetIdhidden field lets us identify which tweet the user is providing feedback for, ensuring we update the correct row in the database. - PreparedStatement: We use this instead of
Statementto eliminate SQL injection risks, a critical security practice. It also simplifies parameter binding. - Radio Buttons: Since all radio buttons share the same
nameattribute (relevante),request.getParameter("relevante")returns the selected value ("Si" or "No"). - Checkboxes: For multiple selections, we use
name="dominio[]"(the square brackets tell the server to expect an array of values).request.getParameterValues()retrieves all selected options, which we join into a comma-separated string (adjust this if your database uses a different format like JSON). - Resource Cleanup: Closing database connections, statements, and result sets in a
finallyblock ensures we don't leave unused resources hanging.
4. Additional Best Practices
- Avoid Scriptlets: While scriptlets work, modern JSP development uses JSTL and EL (Expression Language) for cleaner, more maintainable code. Consider refactoring once you have the basic logic working.
- User-Friendly Errors: Replace stack trace prints with user-friendly messages in production environments.
- Encoding: Ensure all JSP pages use UTF-8 encoding to avoid character display issues (we added this in
Update.jspwithcontentType="text/html;charset=UTF-8").
内容的提问来源于stack exchange,提问作者Fernando
相关产品推荐
相关产品推荐

