jsp实现表单发送数据功能,数据保存到数据库并弹出发送成功或者失败的提示框
时间: 2024-03-05 16:51:54 浏览: 24
要实现将表单数据保存到数据库,可以使用JDBC连接数据库进行操作。下面是一个简单的示例代码:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
// 获取表单数据
String name = request.getParameter("name");
String email = request.getParameter("email");
String message = request.getParameter("message");
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
// 插入数据
String sql = "INSERT INTO messages (name, email, message) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, email);
pstmt.setString(3, message);
pstmt.executeUpdate();
// 发送成功后弹出提示框
out.println("<script>alert('发送成功!');location.href='index.jsp';</script>");
} catch (Exception e) {
e.printStackTrace();
// 发送失败后弹出提示框
out.println("<script>alert('发送失败,请重试!');history.back();</script>");
} finally {
if (pstmt != null) {
try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
%>
```
以上代码中,使用JDBC连接数据库,将表单数据插入到名为messages的表中。如果插入成功,则弹出发送成功的提示框,否则弹出发送失败的提示框。
需要注意的是,这里只是一个简单的示例,实际应用中需要进行更严格的数据验证和安全防范,以避免SQL注入等安全问题。