Skip to main content

Retrieve Data from Database and Compare it with user input using Java

In this Lesson we will create a form page "form.jsp" that takes the user email. After that we will check the user existence in our DB. If the user email stored in the DB, a welcoming page will be opened to him/her. If the user is a new user then a message will be displayed that tells him/her this email is not stored in our DB.
Note: I use access 2013 database and Eclipse Juno
  
Basic step, Create a new project:
Open Eclipse then click on File > New > Other > Web > Dynamic Web Project.

First, Load the DB class:
  • In this step we will connect with database so we will gather all its code in a java class named "DBConnection.java" under a package called "code".
  • Expand your project then right click on java resources > New > Package.
  • After-that Give a name for your package ex, code 
  • Right click on your created new package that called code > New > Class. 
  • After-that Give a name for your Class ex, DBConnection. 
  • Type the code that will connect Eclipse with DB and that will load the JDBC ODBC Driver

The code is:
package yourpackagename.classname; // in this case it will be code.DBConnection
import java.sql.*;
public class DBConnection{

        public Statement st;
        public ResultSet rs;
        public Connection conn;
        public PreparedStatement ps =null;      
           
        public Connection setConnection(){
            try{
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    conn = DriverManager.getConnection("jdbc:odbc:mydsn1");
            }catch(Exception e){
                    e.printStackTrace();
            }
            return conn;
        }
      
        public PreparedStatement precompiled (String query, Connection conn){
            this.conn = conn;
            try{
                    ps = conn.prepareStatement(query);
                  
            }catch(Exception e){
                System.out.println("The Error of ResultSet is" + e);
            }  
            return ps;
        }
      
        public void CloseConn(ResultSet rs, Statement st, PreparedStatement ps, Connection conn){
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }
}


Second, We will create the form.jsp page:
  • Expand your project then right click on WebContent > New > JSP File.
  • After-that Give a name for your JSP page ex, form.jsp
  • Next > choose New JSP File (html) > Finish.
  • Type the code that will take the user email
The code is:  
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>

</head>
<body>

// A form named form that send the user email to Formcode.jsp page to be executed
<form id="form" name="form" method="post" action="Formcode.jsp">
<table>
    <tr>
        <td>Email</td>
        <td><input type="text" name="UEmail" size="20"/></td>
    </tr>
    <tr>

        <td colspan="2">
        <input type="submit" name="submit" value="log in" />
        </td>
    </tr>
</table>
</form>
</body>
</html>


Third, We will create the form.jsp page:
  • Expand your project then right click on WebContent > New > JSP File.
  • After-that Give a name for your JSP page ex, Formcode.jsp
  • Next > choose New JSP File (html) > Finish.
  • Type the code that will check if the entered user email match the user email stored in our DB or not. If the user exist in our DB, we will transport him/her to a new page.
The code is:<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Formcode</title>
</head>
<body>

<%
    //Take user email
    String email = request.getParameter("UEmail");
    //Check if the user entered an email or left it empty
    if (email != null){
        try{
            // Instantiate an instance from the DBConnection class to use it inside this JSP page
            DBConnection dbconn = new DBConnection();
            Statement st = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            Connection conn = null;

            conn = dbconn.setConnection();
          
            // Create a SQL statement that will retrieve the user email from the DB that matching user   email in the Form
            String strquery = "SELECT Email FROM USA WHERE Email= ' "+email+" ' ; ";
          
            st = conn.createStatement();
            rs = st.executeQuery(strquery);         
            try{
                if (rs.next()){
                    /*Transport user to another page using one way from the following:
                      First, response.sendRedirect("yourpage.jsp");
                      Second, RequestDispatcher rd=request.getRequestDispatcher("yourpage.jsp");
                      rd.forward(request,response);*/

                  
                    RequestDispatcher rd=request.getRequestDispatcher("Hello.jsp");
                    rd.forward(request,response);
                }
                // Display a message if the DB is empty
                else{
                        if (! rs.next() ) {
                            System.out.println("This Email is not stored in our DB");
                        }
               }
               //Close all connections                         
               dbconn.CloseConn(rs, st, ps, conn);
            }
            catch (Exception e) {
                out.println(e.toString() + "<br>");
            }
        }
        catch (Exception e) {
            out.println(e.toString() + "<br>");
        }              
    }
    else{
        out.println("Please Enter your Email");
    }
%>

</body>
</html>


Finally, Run your project:
Right click on your project > Run > Run on Server

Upcoming:
In the next Lesson we will learn how to add the new user email to our DB.
.....................done.....................

Comments

Popular posts from this blog

An attempt was made to insert a node where it is not permitted

Do you face this Error while you are writing code to generate xml file from java? Exception in thread "main" org.w3c.dom.DOMException : HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.        at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(Unknown Source)        at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source)        at generatexml.WriteXMLFile.main( WriteXMLFile.java:30 ) Well the answer is: Don't insert the node where it isn't permitted. Change your generated directory file path from 'C' to other directory ex, D or to any directory you have. Make sure the ‘appendChild’ is referring to the right element. Don’t appending twice, only make it once. Ex, //Writetoxml.java   Element rootElement = doc . createElement ( " Company " );   doc . appendChild ( rootElement );                Element subElement = doc . cre

Do you want to know about your computer in one window screen?

System Toolbox (Sys Toolbox) If you want to know information about your computer from processor, drivers, motherboard, memory, operating system,...and more, you can depend on this software. Sys Toolbox (see screen shoot from the software) provides a software and hardware information for windows operating system. It is a simple software that you can use it to know about your PC. To run the software, you need to: Extract the zipped software.  After that, right click on the software icon and choose "Run as administrator". Finally, you will find a pop up screen telling you information about you PC. To go to the software site: http://sys-toolbox-pro.soft112.com/ To Download the software: Download