从jsp页面获取复选框的值并插入数据库!
时间: 2024-03-10 12:49:33 浏览: 15
首先,在JSP页面中需要定义一个或多个复选框,例如:
```
<form action="insert.jsp" method="post">
<input type="checkbox" name="hobby" value="reading">阅读
<input type="checkbox" name="hobby" value="music">音乐
<input type="checkbox" name="hobby" value="sports">运动
<input type="submit" value="提交">
</form>
```
其中,`name`属性的值必须相同,以便在后台代码中获取复选框的值。
接下来,在`insert.jsp`页面中,可以使用`request.getParameterValues()`方法获取复选框的值,并将其插入到数据库中。例如:
```
<%@ page import="java.sql.*" %>
<%
String[] hobbies = request.getParameterValues("hobby");
if(hobbies != null && hobbies.length > 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
PreparedStatement ps = conn.prepareStatement("INSERT INTO user (hobby) VALUES (?)");
for(int i=0; i<hobbies.length; i++) {
ps.setString(1, hobbies[i]);
ps.executeUpdate();
}
ps.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
%>
```
在上面的代码中,首先使用`request.getParameterValues()`方法获取复选框的值,然后使用JDBC连接MySQL数据库,并执行插入操作。需要注意的是,这里使用了`PreparedStatement`对象和占位符,以防止SQL注入攻击。