Registration form in Servlet
In this example you will see how to develop a registration form in Servlet. To develop a registration form you will need to connect your servlet application with database. Here we are using MySQL database.
STEP 1: Create a Table in your Database
create table Student
(
name varchar(60),
email varchar(60),
pass varchar(100)
)
index.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con = DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/test","username","password");
PreparedStatement ps = con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i = ps.executeUpdate();
if(i > 0) {
out.println("You are sucessfully registered");
}
}
catch(Exception se) {
se.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>