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

Error Class names are only accepted if annotation processing is explicitly requested

Do you get the following error? Class names, 'Hello', are only accepted if annotation processing is explicitly requested 1 error In case you got this error, then you forget to add .java to the file name when you compile it So when you want to compile a file using cmd console window write the filename.java extension Example: Javac Hello.java If you write it in this way the error will go away. So don’t forget to include suffix with your file name during compilation.

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 ( ro...

What do you know about HKEY_LOCAL_MACHINE (HKLM)?

What is it? HKEY stands for " Handle to Registry Key ”. The HKEY_LOCAL_MACHINE subtree contains information about the local computer system, including hardware and operating system data, such as bus type, system memory, device drivers, and startup control parameters. It is one of several registry hives in the Windows Registry . HKEY_LOCAL_MACHINE contains the majority of the configuration information for the software you have installed and for the Windows operating system itself. It also contains information about currently detected hardware and, beginning in Windows Vista, information about your computer's boot configuration. HKLM components The following registry keys are located under the HKEY_LOCAL_MACHINE hive: HKEY_LOCAL_MACHINE\BCD00000000 HKEY_LOCAL_MACHINE\COMPONENTS HKEY_LOCAL_MACHINE\HARDWARE HKEY_LOCAL_MACHINE\SAM HKEY_LOCAL_MACHINE\Schema HKEY_LOCAL_MACHINE\SECURITY HKEY_LOCAL_MACHINE\SOFTWARE HKEY_LOCAL_MACHINE\SYSTEM No...