import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class InsertUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve form data
String username = request.getParameter("username");
String email = request.getParameter("email");
// Database connection parameters
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
String dbUser = "your_username";
String dbPassword = "your_password";
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Load the JDBC driver (optional in recent versions)
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
// SQL insert statement
String sql = "INSERT INTO users (username, email) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username); // Set username parameter
pstmt.setString(2, email); // Set email parameter
// Execute the insert
int rowsInserted = pstmt.executeUpdate();
// Send a response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (rowsInserted > 0) {
out.println("<h1>User added successfully!</h1>");
} else {
out.println("<h1>Failed to add user.</h1>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
------------<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add User</title>
</head>
<body>
<h2>Add New User</h2>
<form action="InsertUserServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Add User">
</form>
</body>
</html>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter