MySQL database so creates a database with name db. create a table with name user having three fields fname, email and pass of varchar type.
Dynamic Web Project Name:
reg/anything
Load lib folder:
Mysql connector.jar
Servlet Class Name: regs
regs.java
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/regs")
public class regs extends HttpServlet {
String DB_CONNECTION_URL="jdbc:mysql://localhost:3306/db";
String DB_USERNAME="root";
String DB_PASSWORD="";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname=request.getParameter("fname");
String email=request.getParameter("email");
String pass=request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
PreparedStatement ps=con.prepareStatement("insert into user(fname,email,pass) values(?,?,?)");
ps.setString(1, fname);
ps.setString(2, email);
ps.setString(3, pass);
int re=ps.executeUpdate();
if(re==1){
response.sendRedirect("hello.html");
}
else{
response.sendRedirect("error.html");
}
}catch(Exception e){
}
}
}
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
HTML File:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="regs" method="post">
Name : <br><input type="text" name="fname"/><br>
Email: <br><input type="email" name="email"><br>
Password: <br><input type="password" name="pass"><br>
<input type="submit" value="Registraton">
</form>
</body>
</html>
</head>
<body>
<form action="regs" method="post">
Name : <br><input type="text" name="fname"/><br>
Email: <br><input type="email" name="email"><br>
Password: <br><input type="password" name="pass"><br>
<input type="submit" value="Registraton">
</form>
</body>
</html>
error.html
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Error Page
</body>
</html>
hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Successfully
</body>
</html>
<title>Insert title here</title>
</head>
<body>
Successfully
</body>
</html>
0 on: "Simple Servlet Registration Form with MySQL Database"
Your Comment is processing to approved