JDBC and Servlet Examples - :-


Example 1 -

This example will ask the user to login if the user is already registered, otherwise register yourself and then login based on the credentials specified at the time of registration.




Note - If you are new to JDBC, we will recommend you to first refer to JDBC tutorials. Click here to learn JDBC
Here we are using MySQL RDBMS -
1- First of all create a database named mydatabase.
2- Within mydatabase create a table named userinfo as follows -
Name Password Email Mobile


Now get back to java application and create the following files -
1- index.html or index.jsp - This will be your default page and Login Form
<!DOCTYPE html>
<html>
    <head>
        <title>JDBC and Servlet Demo</title>
    </head>
    <body>
          <form method="get" action="LoginChk">
            <table border="1px">
                <tr>
                    <td>Enter Email -</td>
                    <td><input type="email" name="t1"></td>
                </tr>
                <tr>
                    <td>Enter Password -</td>
                    <td><input type="password" name="t2"></td>
                </tr>
                <tr>
                    <td><a href="Register.html">Register Here</a></td>
                    <td><input type="submit" value="Login"></td>
                </tr>
                
            </table>
             
        </form>
    </body>
</html>        

2- Register.html - Create a html file named Register.html. It will be our Registration form.
<!DOCTYPE html>
<html>
    <head>
        <title>Registration Form</title>
    </head>
    <body>
         <form method="post" action="Register_Info">
            <table border="1px">
                <tr>
                    <td>Name -</td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td>Password -</td>
                    <td><input type="password" name="t2"></td>
                </tr>
                <tr>
                    <td>Email ID -</td>
                    <td><input type="email" name="t3"></td>
                </tr>
                <tr>
                    <td>Mobile -</td>
                    <td><input type="tel" name="t4"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Register"></td>
                </tr>
                
            </table>
             
        </form>
    </body>
</html>        

3- Create a package named servs, and within that create the following servlets -
Register_Info Servlet - This servlet will be used to store user registration information into database.
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Register_Info extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try
        {
          out = response.getWriter();
          String name = request.getParameter("t1");
          String pass = request.getParameter("t2");
          String email = request.getParameter("t3");
          String mobile = request.getParameter("t4");
          String dob = request.getParameter("t5");
          
          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","");
          PreparedStatement ps = con.prepareStatement("insert into userinfo (Name,Password,Email,Mobile) values (?,?,?,?)");
          ps.setString(1, name);
          ps.setString(2, pass);
          ps.setString(3, email);
          ps.setString(4, mobile);
          int val = ps.executeUpdate();
         
          if(val != 0)
          {
              out.println("<h1>Registered Successfully</h1>");
              RequestDispatcher rdp = request.getRequestDispatcher("index.html");
              rdp.include(request, response);
          }
          else
          {
              response.sendRedirect("Register.html");
          }
        }
        catch(Exception ex)
        {
            out.println(ex);
        }
    }
}
    

LoginChk Servlet - This servlet will be used to check user email and password from database, If valid credentials provided by user, he will be redirected to Home page, otherwise Login page with error message will be displayed.

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class LoginChk extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try
        {
            out = response.getWriter();
    
            String email = request.getParameter("t1");
            String pass = request.getParameter("t2");
            
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","");
            PreparedStatement ps = con.prepareStatement("select * from userinfo where email=?");
            ps.setString(1, email);
            ResultSet rs = ps.executeQuery();
            String dbpass = null;
            if(rs.next())
            {
                dbpass = rs.getString(2);
            }
            
            if(pass.equals(dbpass))
            {
                response.sendRedirect("Home");
            }
            else
            {
                out.println("<h1 style = 'color:red'>Wrong username or password</h1>");
                RequestDispatcher rdp = request.getRequestDispatcher("index.html");
                rdp.include(request, response);
            }
            
        }
        catch(Exception ex)
        {
            out.println(ex);
        }
    }
}

Home Servlet - This will be our home page, where user will reach if entered correct credentials.

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1 style='text-align:center; padding:10px'>Welcome to Home</h1>");
            out.println("<hr>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

4 web.xml - Add the information of Servlets in web.xml as follows -
<web-app>
    <servlet>
        <servlet-name>Register_Info</servlet-name>
        <servlet-class>servs.Register_Info</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Register_Info</servlet-name>
        <url-pattern>/Register_Info</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>LoginChk</servlet-name>
        <servlet-class>servs.LoginChk</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginChk</servlet-name>
        <url-pattern>/LoginChk</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>servs.Home</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping>
</web-app>        

Note - Do not forgot to include MySQL Connector jar file into your project.

Now run the project and it will show you Login form as follows -



For new user click on Register link and it will show you Registration form as follows -



Fill the form and enter Register button, it will store enterd data in database and redirect you to Login form, now enter email and password -



If you enter valid credentials, It will redirect you to home page as follows -



Note - you can also perform session and cookie managment in the above example, as described in Session Managment section.