Servlets and JDBC (User authentication)

For : Beginners and Intermediate (Those who have basic knowledge on JDBC, Java, Servlets)

This tutorial will tell you about the JDBC connection with Servlet and let to update or insert of query the Database table based on the dynamic Queries. Also this Example will show you how to authenticate a user based on the data stored in the Database Table

Step 1: To create a DSN name, and to create a Database using MS Access, see this Post

Following is the table structure: Name of the table is student

regno password
pradeepkumar hellohowareyou
amiitesh welcome

 

Create a HTML Form that asks for a username and Password

FileName: msindex.html

<html>
<head>
  <title> Form Processing </title>
</head>

<body>
  <form method="post" action="FormServlet">
  Enter your username : <input type="text" name="regno"><br>
  Enter your Password : <input type="password" name="password"><br>
  <input type="submit">
  </form>
</body>
</html>

FileName: FormServlet.java

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

public class FormServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
    {
        res.setContentType("text/html");
        ServletOutputStream out=res.getOutputStream();
        String s1=req.getParameter("user");
        String s2=req.getParameter("password");
        out.println("<html><body>");
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //JDBC ODBC Driver
        }
        catch (Exception e)
        {
            out.println("Driver Issues"+e.getMessage());
        }
        try
        {
            Connection con=DriverManager.getConnection("jdbc:odbc:pradeep");
            Statement stmt=con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from student where regno='"+s1+"' and password='"+s2+"'");
            int count=0;
            while(rs.next())
            {
                count++;
            }
            if(count>0)
                out.println("Success"+s1+"You are authenticated");
            else
            {
                out.println("Your password or username is wrong");
                //res.sendRedirect("form.html");
            }
        }
        catch (SQLException ee)
        {
            out.println("DSN Issues"+ee.getMessage());
        }
    }
}

Compile the file and Make an entry in the web.xml file and run the HTML file using the link http://localhost:8080/examples/msindex.html

Provide a name and password (which is there in the student table given above) and click Submit. You can see a page that authenticates you, if your username and password are correct, else it will show you a warning message.

Comments

Popular Posts