0% found this document useful (0 votes)
14 views2 pages

J 1

This document is a Java servlet code for user registration using JDBC to connect to a MySQL database. It handles POST requests to insert a username and password into a 'users' table and provides feedback on the registration status. Error handling is included to manage SQL exceptions during the database operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

J 1

This document is a Java servlet code for user registration using JDBC to connect to a MySQL database. It handles POST requests to insert a username and password into a 'users' table and provides feedback on the registration status. Error handling is included to manage SQL exceptions during the database operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd

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