Creating a Method to Authenticate Users

In the following steps, you create a method in the DataHandler.java class that authenticates users by checking that the values they supply for the userid and password match those required by the database schema.

  1. Open the DataHandler.java class in the Source Editor.
  2. Create a method called authenticateUser that checks if the userid, password, and host values supplied by a user are valid:
    public boolean authenticateUser(String jdbcUrl, String userid, String password,
      HttpSession session) throws SQLException {
     
    }
    
  3. JDeveloper prompts you with a wavy underline and a message that you must import a class for HttpSession. Press the Alt+Enter keys to import the javax.servlet.http.HttpSession class.
  4. Within the body of the method, assign the jdbcUrl, userid, and password values from the call to the attributes of the current object as follows:
    this.jdbcUrl= jdbcUrl;
    this.userid = userid;
    this.password = password;
    
  5. Attempt to connect to the database using the values supplied, and if successful, return a value of true. Enclose this in a try block as follows:
    try {
      OracleDataSource ds;
      ds = new OracleDataSource();
      ds.setURL(jdbcUrl);
      conn = ds.getConnection(userid, password);
      return true;
    }
    

    See Also:

    For information about using try and catch blocks, refer to Exception Handling in Updating Data.

  6. To handle the case where the login credentials do not match, after the try block, add a catch block. The code in this block prints out a log message and sets up an error message. This error message can be displayed to the user if a login attempt fails. The jdbcUrl, userid and password variables are set back to null, and the method returns the value false. To do this, enter the following code:
    catch ( SQLException ex )  {
      System.out.println("Invalid user credentials");
      session.setAttribute("loginerrormsg", "Invalid Login. Try Again...");
      this.jdbcUrl = null;
      this.userid = null;
      this.password = null;
      return false;
    } 
    

Example 4-4 Implementing User Validation

public boolean authenticateUser(String jdbcUrl, String userid, String password,
  HttpSession session) throws SQLException {
 
  this.jdbcUrl = jdbcUrl;
  this.userid = userid;
  this.password = password;
  try {
    OracleDataSource ds;
    ds = new OracleDataSource();
    ds.setURL(jdbcUrl);
    conn = ds.getConnection(userid, password);
    return true;
  } catch ( SQLException ex )  {
  System.out.println("Invalid user credentials");
  session.setAttribute("loginerrormsg", "Invalid Login. Try Again...");
  this.jdbcUrl = null;
  this.userid = null;
  this.password = null;
  return false;
  } 
}

The complete code is shown in Example 4-4.