DataBase Connectivity and validation of data from Oracle Database in JAVA Servlet

In this article you will learn how to connect to a Database and validate the data in a Java Servlet.

Introduction

 
This article is the next in the series of articles about Java Servlet. In this article, we make an application and we will learn about how to Connect the Database and validate the username and password from the Database enter from the Login page. In this application, we are using Oracle Database 10g. First of all, we make a Database table for login validation. Steps to create a table in Oracle Database are given below:
 
Step-1: Install the Oracle Database. After Installing , Go to Start-> All  Programs-> Oracle Database 10g Express Edition-> Run SQL Command Line click it. A run SQL command prompt appears. 
 
Runsqlcommandline 
 
opencommand 
 
Step-2: First type connect or conn. Press Enter key then  Enter user-name system again. Press Enter key then Enter Password. This password is same as installation time but by default we use tiger or scott. Press Enter key now you are connected to the Oracle Database.
 
connectedoracle.gif 
 
Step-3: Now we are creating a Table. Creating tables is done with the create table command. The create table command does the following:
  • Defines the table name
  • Defines the columns in the table and the datatypes of those columns
  • Defines what tablespace the table resides in (optional)
  • Defines other characteristics of the table (optional)
Let's look at the create table command in action:  
  1. create table loginvalidation(username varchar2(20) primary key , password number(5)  not null);  
In this example, we create a table called loginvalidation which has 2 columns. The first column is username which is a VARCHAR2 datatype. This means we will be storing VARCHAR2 in this column. Did you notice on the line where we define the column username, that we included the word primary key? This is known as an in-line constraint because we are defining the constraint on the same line as the column associated with the constraint. What is a primary key constraint? A constraint is a rule that is applied to the table. In this case, the primary key constraint is a rule says can't have a duplicate entry in the username column, and the username column can never be empty or "null". The Second column is password which is a NUMBER datatype. This means we will be storing NUMBER in this column that includes the word not null. When we define a column to be NOT NULL, that means it cannot have a NULL value assigned. This eliminates the problem of three-valued logic very nicely, but may not always be possible when designing tables. 
 
Step-4: Insert the value into the Table.
 
Let's look at the insert value into the table command in action: 
  1. insert into loginvalidation values('admin' ,12345);   
By using this command, 1 row is created into the loginvalidation table and values are admin and 12345. Here we can stored 2 records into the database. Now close the command prompt. 
 
Table.gif 
 
Step-5: Open the eclipse, Select File-> New-> Dynamic web project. Fill up all the Entry and press Finish button. A new project is displayed into the Project Explorer. Here the Project Name is ServletLoginDetails.
 
Step-6: Now create Login.html, reg.html, home.html page.  We make these pages as follows:
 
Right click on project -> new -> Html page.
 
Login.html
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  5. <title>Login page</title>  
  6. </head>  
  7. <body>  
  8. <center>  
  9. <form action="./firstserv" method="post">  
  10. username      
  11. <input type="text" name="username" />  
  12. <br>  
  13. <br>  
  14. password      
  15. <input type="password" name="password"></input><br><br>  
  16.      
  17. <input type="submit" value="login"></input>  
  18.      
  19. <a href="./reg.html">new user</a>  
  20. </form>  
  21. </center>  
  22. </body>  
  23. </html>  
home.html
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  5. <title>Home page</title>  
  6. </head>  
  7. <body>  
  8. home page under construction...............  
  9. make a home page ...........  
  10. </body>  
  11. </html>  
reg.html
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  5. <title>Registration Form</title>  
  6. </head>  
  7. <body>  
  8. registration page under construction...............  
  9. make a registration form.  
  10. </body>  
  11. </html>  
Step-7: Now create Servlet as follows   

Right-click on project -> new -> Servlet. And fill up all the Entry here the name of Servlet is SerExam.

SerExam.java
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import java.sql.*;  
  4. import javax.servlet.RequestDispatcher;  
  5. import javax.servlet.ServletConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. public class SerExam extends HttpServlet   
  11. {  
  12.       Connection con;  
  13.       PreparedStatement ps;  
  14.       ResultSet rs;  
  15.       public void init(ServletConfig config)throws ServletException  
  16.       {   
  17.             try   
  18.                {  
  19.                         Class.forName("oracle.jdbc.driver.OracleDriver");  
  20.                         con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");   
  21.                }   
  22.                   catch (ClassNotFoundException e)  
  23.                      {  
  24.                         System.out.println(e);  
  25.                      }   
  26.                   catch (SQLException e)   
  27.                      {  
  28.                         System.out.println(e);  
  29.                      }  
  30.       }  
  31.       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException   
  32.       {  
  33.             doPost(request, response);  
  34.       }  
  35.       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException   
  36.       {  
  37.             response.setContentType("text/html");  
  38.             PrintWriter pw=response.getWriter();  
  39.             String username=request.getParameter("username");  
  40.             String password=request.getParameter("password");  
  41.             pw.println("<html><body>");  
  42.             try   
  43.             {  
  44.                   ps=con.prepareStatement("select * from loginvalidation where username=? and password=?");  
  45.                   ps.setString(1, username);  
  46.                   ps.setString(2, password);  
  47.                   rs=ps.executeQuery();  
  48.                   if(rs.next())  
  49.                   {  
  50.                         pw.println("<h3>welcome " +" " + username +"</h3>");  
  51.                         RequestDispatcher rd1=request.getRequestDispatcher("./home.html");  
  52.                         rd1.include(request,response);  
  53.                         //or  
  54.                         //response.sendRedirect("./home.html");  
  55.                         pw.println("<form method=\"post\" action=\"Login.html\">");  
  56.                         pw.println("<input type=\"submit\" name=\"logout\" " + "value=\"Logout\">");  
  57.                         pw.println("</form>");  
  58.                           
  59.                   }  
  60.                   else  
  61.                   {  
  62.                         pw.println("<center><h3>invalid username/password Enter Correct username/password</h3></center>");  
  63.                         RequestDispatcher rd2=request.getRequestDispatcher("./Login.html");  
  64.                         rd2.include(request,response);  
  65.                         //or  
  66.                         //response.sendRedirect("./Login.html");  
  67.                   }  
  68.             }  
  69.             catch (SQLException e)   
  70.                   {  
  71.                   e.printStackTrace();  
  72.                   }  
  73.       }  
  74. }  
Step-8: Create a web.xml file if u use Eclipse IDE by default created by IDE then modify the url pattern as follows:
 
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd%22%20id=%22WebApp_ID%22%20version=%222.5 id="WebApp_ID" version="2.5">  
  3.   <servlet>  
  4.     <servlet-name>SerExam</servlet-name>  
  5.     <servlet-class>SerExam</servlet-class>  
  6.   </servlet>  
  7.   <servlet-mapping>  
  8.     <servlet-name>SerExam</servlet-name>  
  9.     <url-pattern>/firstserv</url-pattern>  
  10.   </servlet-mapping>  
  11. </web-app>  
Step-8: Right Click on Project or application -> Run As -> Run on Server. Browser is open and at the end of URL enter the Login.html.
 
For example: http://localhost:9999/ServletLoginDetails/Login.html. Enter the username and password in text boxes and click on login button.
 
Loginpage.gif 
 
If the username and password are valid then you see the url is changed that is this page is redirect to the given url pattern in web.xml file. 
 
validuser.gif 
 
If the username and password are not valid then you see the url is not changed (http://localhost:9999/ServletLoginDetails/firstserv) but we are in Login.html page with a message because we are using the RequestDispatcher rather than sendRedirect.
 
invaliduser.gif 
 
If we click the newuser hyperlink the url also changed http://localhost:9999/ServletLoginDetails/reg.html.
 
reguser.gif 
 

Summary 

 
I think it will be helpful for you to create this type of application.