J 1

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

import java.io.

IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final String JDBC_URL =
"jdbc:mysql://your_database_host:your_database_port/your_database
_name";
private static final String JDBC_USER =
"your_database_username";
private static final String JDBC_PASSWORD =
"your_database_password";

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String username = request.getParameter("username");


String password = request.getParameter("password");

try (Connection connection =


DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASSWORD)) {
String query = "INSERT INTO users (username, password)
VALUES (?, ?)";
try (PreparedStatement preparedStatement =
connection.prepareStatement(query)) {
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);

int rowsAffected =
preparedStatement.executeUpdate();
if (rowsAffected > 0) {
out.println("Registration successful!<br>");
out.println("Username: " + username + "<br>");
out.println("Password: " + password + "<br>");
} else {
out.println("Registration failed. Please try
again.<br>");
}
}
} catch (SQLException e) {
e.printStackTrace();
out.println("Error: " + e.getMessage());
}
}
}

You might also like