Login API
Overview Login
JavaScriptValidation ControllerService
DataModel MYSQL Commands
CSS StyleSheet

Overview

Get the email and password input from the user using HTML form. Validate the user's email and password fields to make sure they are not empty(null) using JavaScript function. If all is good send the email and password to the backend, In our case it is a Servlet hosted in Glassfish container. Note that this is not tied to just GlassFish. it can be deployed onto any container than can host Servlet's and Jsp's. Servlet looks up the username in our case 'email' and if found then looks up and try's to match the password of the user. If success it creates a user-object and put's the user-object into HTTP session and rout's the user to welcome page. If the email or password do not match, Servlet rout's the user to login fail page.


User login design doc


 ᐱ 

Login

HTML login form two input fields , 2 labels and a Sign In button. When the user click the submit/sign in button first the JavaScript is called. Javascript checks for nulls. If they are not null/empty the Javascript method returns true and the input parameters are passed to the backend Servlet(ServletLoginService).

Sample login screen


 ᐱ 
JavaScript Validation

Once the user clicks ?Sign In? button. JavaScript validations method is invoked. Most browsers have a JavaScript debuggers build in if you want to follow your code during execution. Always a good JavaScript debug tool, Look into browser developer console. JavaScript method validates to make sure we do not have empty string as inputs, if all is good then it returns true and the action is passed to the Servlet.


            
function validateLogin(frm)
{
    event.preventDefault();

    if (frm.email.value == "")
    {
        alert("User Name can not be left blank");
        frm.email.focus();
        return false;
    }
    if (frm.password.value == "")
    {
        alert("Password can not be left blank");
        frm.password.focus();
        return false;
    }
    document.loginForm.submit();
}
            
                        


 ᐱ 
Controller Service

In the init method of our Servlet we initialize the database(DB) connection object. In our case we will get the DB connection from the container JDBC pool. Code to get the sql connection is pretty straight forward. Setting up the DB Connection pool and the JNDI name in the container will be explained in a Glassfish setup section of the documentation, Where we also talk about setting up ssh, log4J, mysql along with various optimizations. Login Servlet first looks up, if the email exists in the users table if it does then try's to match the password. If there is a match we create the UserObject basically a Object that contains all the attributes of the user and put it in the http session object. it will direct the request to index.jsp page. By putting the UserObject in session the view(Jsp?s) can introspect and use the User Object attributes as needed. Session timeout is externalized and maintained by the Container(Glassfish). if there is no match it will be routed to loginfail.jsp.


            
import com.jcarx.db.NetAppsJNDIUserDB;
import com.jcarx.db.UserObject;
import com.jcarx.util.NetClientHeaderInfo;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/**
 *
 * @author Ravi Manthena
 */
public class ServletLoginService extends HttpServlet {

    InitialContext ctx = null;
    DataSource ds = null;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    private static final long serialVersionUID = 1L;
    static Logger log = Logger.getLogger(ServletLoginService.class);

    public void init() throws ServletException {
        try {
            ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("jdbc/NetMYSQLJNDI");
            conn = ds.getConnection();
            System.out.println(conn.toString());
            log.debug(conn.toString());
        } catch (SQLException se) {
            log.error("SQLException: " + se.getMessage());
        } catch (NamingException ne) {
            log.error("NamingException: " + ne.getMessage());
        }
    }

    /**
     * Processes requests for both HTTP 
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        HttpSession session = request.getSession();
        log.debug(session);
        NetAppsJNDIUserDB jndiuserdb = new NetAppsJNDIUserDB();

        if(conn == null){          
            this.init();
            log.debug("connection was null so init again"+conn.toString());
        }else{
            log.debug("connection was not null so reusing"+conn.toString());
        }
        
        if (jndiuserdb.getuserExists(conn, email)) {
            UserObject userObject = jndiuserdb.getUserUsingemail(conn, email);
            if (userObject.pass.equals(password)) {
                jndiuserdb.setupdatelogin(conn, email, com.jcarx.util.Utility.getTimeStr());
                userObject = jndiuserdb.getUserUsingemail(conn, email);
                session.getServletContext().setAttribute("userObject", userObject);
                response.sendRedirect("index.jsp");
                String clientip = NetClientHeaderInfo.getClientIp(request);
                jndiuserdb.setupdateclientip(conn,email,clientip);
                log.info("logged in successfully:"+userObject.name+" ip:"+clientip);
            } else {
                response.sendRedirect("loginfail.jsp");
                log.error("logged in failed for " + email);
            }
        } else {
            response.sendRedirect("loginfail.jsp");
            log.error("logged in failed for " + email + " doesn't exists");
        }
        if (conn != null) {
            try {
                log.debug("SQL Connection Closed="+conn.toString());
                conn.close();
                conn = null;
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    }

    /**
     * Handles the HTTP GET
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
            
                        


            
package com.jcarx.db;

public class UserObject {
    public String email;
    public String pass;
    public String name;
    public String status;
    public int emailcount;
    public String lastlogin;
    public String uuid;
    public String admin;
}

            
                        


 ᐱ 
DataModel

Write a database Object all it should know about is take your DB connection which we pass to it and any action related to DB we want to execute. This object has all the helper methods to insert/delete/lookup/update the Users table. Database helper object contains all the helper method more than just for login API. Just a note make sure you close the sql connection when your query is done. Best place to do it is in the Servlet and not the Database helper Object. Use the Servlet as a Controller use the same sql connection object as many times as you need and close it when done. This will reduce opening and closing database connections multiple times. If you go through the code in ServletLoginService you will see how the sql connection is created used by the Servlet(Controller) and close when done using it. If you do not close the connection the container may run out of SQL connection and hang overtime.


            
package com.jcarx.db;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.log4j.Logger;

public class NetAppsJNDIUserDB {

    static Logger log = Logger.getLogger(NetAppsJNDIUserDB.class);

    public String isAdmin(Connection con, String email) {
        try {
            String sql = "SELECT * from admin WHERE email='" + email + "';";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            if (rs.next()) {
                return "yes";
            } else {
                return "no";
            }

        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return "no";
        }
    }

    public Object adminRun(Connection con, String dbsql) {
        try {
            Object obj = null;
            Statement stmt = con.createStatement();
            return stmt.executeQuery(dbsql);
        } catch (Exception x) {
            StringWriter sw = new StringWriter();
            x.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            log.error(exceptionAsString);
            return null;
        }
    }

    public boolean dropDB(Connection con, String dbsql) {
        try {
            String sql = dbsql;

            Statement stmt = con.createStatement();
            stmt.executeUpdate(sql);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return false;
        }
        return true;
    }

    public String createuserstableDB(Connection con, String sqlStr) {
        String result = "Success";
        try {
            Statement stmt = con.createStatement();
            stmt.executeUpdate(sqlStr);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return result;
    }

    public String dropuserstableDB(Connection con, String sqlStr) {
        String result = "Success";
        try {
            Statement stmt = con.createStatement();
            stmt.executeUpdate(sqlStr);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return result;
    }

    public String insertuserstableDB(Connection con, String sqlStr) {
        String result = "Success";
        try {
            Statement stmt = con.createStatement();
            stmt.executeUpdate(sqlStr);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return result;
    }

    public int insertuserDB(Connection con, String email, String password,
            String name, String status, int emailcount, String lastlogin, String uuid, String admin) {
        try {
           String sql = "insert into users "
                    + "VALUES('" + email + "','" + password + "','" + name + "','" + status
                    + "','" + emailcount + "','" + lastlogin + "','" + uuid + "','"+ admin + "','"+ "none" + "');";
            Statement stmt = con.createStatement();
            return stmt.executeUpdate(sql);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return 0;
        }
    }

    public String sqlselectall(Connection con) {
        StringBuilder buf = new StringBuilder();
        buf.append("ResultSet....\n");
        try {
            String sql = "Select * from users;";
         Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                buf.append(rs.getString("email") + " ");
                buf.append(rs.getString("password") + " ");
                buf.append(rs.getString("name") + " ");
                buf.append(rs.getString("status") + " ");
                buf.append(rs.getString("lastlogin") + " ");
                buf.append(rs.getString("uuid") + " ");
                buf.append(rs.getString("admin") + " \n\n");
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            buf.append(x.getMessage());
            return buf.toString();
        }
        return buf.toString();
    }

    // access allowed, suspended
    public String getuserStatus(Connection con, String email) {
        try {
            String sql = "Select status from users "
                    + "WHERE email = '" + email + "'";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                return rs.getString("status");
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return "none";
    }

    public int getemailcount(Connection con, String email) {
        int emailcount = 0;
        try {
            String sql = "Select emailcount from users "
                    + "WHERE email = '" + email + "'";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                //Retrieve by column name
                return rs.getInt("emailcount");
            }
        } catch (Exception x) {
            log.error(x);
            x.printStackTrace();
        }
        return emailcount;
    }

    public boolean getuserExists(Connection con, String email) {
        try {
            String sql = "Select email from users "
                    + "WHERE email = '" + email + "'";
            log.debug(sql);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String emailrs = rs.getString("email");
                if (emailrs.equalsIgnoreCase(email)) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
        }
        return false;
    }

    public String getuserlastlogin(Connection con, String email) {
        try {
            String sql = "Select lastlogin from users "
                    + "WHERE email = '" + email + "'";
            log.debug(sql);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                return rs.getString("lastlogin");
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
        }
        return "none";
    }

     public String getuseruuid(Connection con, String uuid) {
        try {
            String sql = "Select uuid from users "
                    + "WHERE uuid = '" + uuid + "'";
            log.debug(sql);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                return rs.getString("uuid");
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
        }
        return "none";
    }

    public UserObject getUserUsingemail(Connection con, String email) {
        UserObject userobject = new UserObject();
        try {
            String sql = "Select email,password,name,status,emailcount,lastlogin,uuid,admin from users "
                    + "WHERE email = '" + email + "'";
            log.debug(sql);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                userobject.email = rs.getString("email");
                userobject.pass = rs.getString("password");
                userobject.name = rs.getString("name");
                userobject.status = rs.getString("status");
                userobject.lastlogin = rs.getString("lastlogin");
                userobject.uuid = rs.getString("uuid");
                userobject.admin = rs.getString("admin");
                return userobject;
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return null;
        }
        return userobject;
    }

    public UserObject getUserUsinguuid(Connection con, String uuid) {
        UserObject userobject = new UserObject();
        try {
            String sql = "Select email,password,name,status,lastlogin,uuid,admin from users "
                    + "WHERE uuid = '" + uuid + "'";
            log.debug(sql);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                userobject.email = rs.getString("email");
                userobject.pass = rs.getString("password");
                userobject.name = rs.getString("name");
                userobject.status = rs.getString("status");
                userobject.lastlogin = rs.getString("lastlogin");
                userobject.uuid = rs.getString("uuid");
                userobject.admin = rs.getString("admin");
                return userobject;
            }
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return null;
        }
        return userobject;
    }

    public int setemailcount(Connection con, String email, int emailcount) {
        try {
            String sqlUpdate = "UPDATE users "
                    + "SET emailcount =" + emailcount
                    + " WHERE email = '" + email + "'";
            Statement stmt = con.createStatement();
            return stmt.executeUpdate(sqlUpdate);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return 0;
        }
    }

    public String setupdatestatus(Connection con, String uuid, String status) {
        try {
            String sqlUpdate = "UPDATE users "
                    + "SET status = '" + status + "'"
                    + "WHERE uuid = '" + uuid + "'";
            Statement stmt = con.createStatement();
            stmt.executeUpdate(sqlUpdate);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return "Status Updated to " + status;
    }
    
    public int setupdateclientip(Connection con, String email, String clientip) {
        try {
            String sqlUpdate = "UPDATE users "
                    + "SET clientip = '" + clientip + "'"
                    + "WHERE email = '" + email + "'";
            Statement stmt = con.createStatement();
            return stmt.executeUpdate(sqlUpdate);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return 0;
        }
    }

    public String setupdatelogin(Connection con, String email, String lastlogin) {
        try {
            String sqlUpdate = "UPDATE users "
                    + "SET lastlogin = '" + lastlogin + "'"
                    + "WHERE email = '" + email + "'";
            Statement stmt = con.createStatement();
            stmt.executeUpdate(sqlUpdate);
        } catch (Exception x) {
            x.printStackTrace();
            log.error(x);
            return x.getMessage();
        }
        return "lastlogin Updated to " + lastlogin;
    }
}
            
                        


 ᐱ 
MYSQL Commands

Login as mysql root user.

Shell> mysql -u root -p
(it will ask for root password)

Once logged in as root, Create a db use, which will be used for all the application layer.

mysql create user 'dazy'@'localhost' identified by 'dazyxyz7';

The above command creates a new user named dazy with a password dazyxyz7. Now we need to give/set privileges to the user dazy, So that the user can create/delete/insert/update tables. Here is the command for that. In our case we will give all privileges to dazy.

mysql GRANT ALL PRIVILEGES ON *.* TO 'dazy'@'localhost' WITH GRANT OPTION;

Also to make sure to run the following command after granting the privileges


mysql FLUSH PRIVILEGES;

then exit out of the mysql shell by typing exit.

mysql exit

Now it's time to login as dazy user.

Shell> mysql -u dazy -p
(type password(dazyxyz7)

now that we are logged in as dazy, time to create a database/tables

mysql create database mydb;

The above command creates a database named mydb, to use this database

run the below command

mysql use mydb;

Some test command for fun.

mysql show tables
mysql desc users;

Let's create users table. You can create a .sql file basically a text file with all your SQL and feed it to mysql command, it's a quick and easy way to drop/create/update/alter tables. Commands to feed a sql file which contains all your sql.


Relative Path
mysql source your.sql


Absolute Path Linux
mysql source /home/dazy/mysqlfile/your.sql


Fullpath Windows
mysql source c:\mywindowspathtomyfile\your.sql


or You can always run any sql comments manualy example to create a users table you can run the below command.


            
            mysql CREATE TABLE `users` (
            `email` varchar(100) NOT NULL,
            `password` varchar(100) NOT NULL,
            `name` varchar(100) NOT NULL,
            `status` varchar(15) NOT NULL,
            `emailcount` int NOT NULL,
            `lastlogin` varchar(19) NOT NULL,
            `uuid` varchar(40) NOT NULL,
            `admin` varchar(4) NOT NULL DEFAULT 'no',
            PRIMARY KEY (`email`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
             
                        
 ᐱ 
CSS Style Sheet

Style sheet for the whole project is defined in one externalized css file. Bootstrap css is also include to handle resizing of the content based on viewer screen size. Bootstrap has a lot of features which make it easier for developing content for web and mobile device rendering etc. You can learn more by visiting getbootstrap.com. As far as styling for this project it is defined in one main CSS file which can be used as ref in your own customization. Here you can download the entire css for your reference.



Download :   netappsmodern.css

Be the first to comment


 Register   123 easy steps Secure Or Comment as Guest

Your Comment

HTML tags allowed Render HTML   
Notify me by email of new comments
Email
hover over for pin

Your PIN