import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UpdateEmailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get user input from request
String userId = request.getParameter("id");
String newEmail = 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 {
// Step 1: Load the JDBC driver (optional in recent JDBC versions)
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish connection to the database
conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
// Step 3: Create SQL update query
String sql = "UPDATE users SET email = ? WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, newEmail); // set email parameter
pstmt.setInt(2, Integer.parseInt(userId)); // set id parameter
// Step 4: Execute update
int rowsUpdated = pstmt.executeUpdate();
// Step 5: Handle response based on update result
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (rowsUpdated > 0) {
out.println("<h1>Email updated successfully for user ID: " + userId + "</h1>");
} else {
out.println("<h1>No user found with ID: " + userId + "</h1>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close resources
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>Update Email</title>
</head>
<body>
<h2>Update User Email</h2>
<form action="UpdateEmailServlet" method="POST">
<label for="id">User ID:</label>
<input type="text" id="id" name="id" required><br><br>
<label for="email">New Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Update Email">
</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