Choose Your Language

Thursday 25 April 2013

Simple Login Application Using JSP Servlets MySQL and Tomcat

index.jsp

<%--
    Document   : index
    Created on : 30 Dec, 2012, 10:39:52 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page language="java"  %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>       
        <form method="get" action="/AppContextPath/LoginServlet">
        <table>               
            <tr>
                <td></td>
                <td align="left">username</td>
                <td><input type="text" name="uname"/></td>
                <td></td>                               
            </tr>
            <tr>
                <td></td>
                <td align="left">password</td>
                <td><input type="password" name="upassword"/></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td><input type="submit" value="submit"></td>
                <td></td>
            </tr>
               
            </table>
        </form>
    </body>
</html>

UserBean.java
public class UserBean {
    private int uid;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
   
     private String username;
     private String password;
     private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
     private String lastName;

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }
     public boolean valid;
}


LoginServlet.java
 import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 public class LoginServlet extends HttpServlet {
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            UserBean user=new UserBean();
            user.setUsername(request.getParameter("uname"));
            user.setPassword(request.getParameter("upassword"));
            user=UserDAO.login(user);
          
            if(user.isValid()){
                HttpSession session=request.getSession(true);
                session.setAttribute("currentSessionUser", user);
                response.sendRedirect("userLogged.jsp");               
            }
            else{
                response.sendRedirect("index.jsp");
            }
        }
        catch(Throwable  theException){
            System.out.println("Exception is"+theException);
           
        }    
    }
}

ConnectionManager.java
import java.sql.*;
import java.util.*;
/**
 *
 * @author Aravind Sankaran
 */
public class ConnectionManager {
    static Connection con;
    static String url="jdbc:mysql://localhost:3306/databasename?";
    static String userName = "dbusername";
    static String password = "dbpassword";
   
    public static Connection getConnection() {
    try {
       Class.forName("com.mysql.jdbc.Driver");
                try {
                con = DriverManager.getConnection(url,userName,password);
                System.out.println("connection success");
                }
            catch(SQLException ex){
                System.out.println(ex);
                 }
        }
    catch(ClassNotFoundException e){
        System.out.println(e);
         //e.printStackTrace();
        }
    return con;
    }
}

UserDAO .java 

public class UserDAO {
 static Connection currentConnection = null;
    static ResultSet rs = null;
    static PreparedStatement preparedStatement = null;
    static PreparedStatement preparedStatement1 = null;
    public static UserBean login(UserBean bean){
        Statement statement=null;   
        String userName=bean.getUsername();
        String userPassword=bean.getPassword();
        String searchQuery="select * from usertable where username='"+userName+"' AND password='"+userPassword+"'";
        System.out.println("before getting connection your given user name is"+userName);
        System.out.println("before getting connection your given user password is"+userPassword);
        System.out.println("your searchQuery is"+searchQuery);
        try{
            currentConnection=ConnectionManager.getConnection();
            statement=currentConnection.createStatement();
            rs=statement.executeQuery(searchQuery);
            boolean more=rs.next();
            if(!more){
                System.out.println("not a registered user");
                bean.setValid(false);;
            }
            else if(more){
                String firstName=rs.getString("firstname");
                String lastName=rs.getString("lastname");
                System.out.println("welcome "+firstName+" "+lastName+"");               
                bean.setFirstName(firstName);
                bean.setLastName(lastName);
                bean.setValid(true);
            }
           
        }
        catch(Exception ex){
            System.out.println("login failed"+ex);
            }
        finally{
            if(rs!=null){
                try{
                    rs.close();
                    }
                catch(Exception e){}                  
                rs=null;
            }
            if(statement!=null){
                try{
                    statement.close();
                }
                catch(Exception e){}
                statement=null;
            }
            if(currentConnection!=null){
                try{
                    currentConnection.close();
                }
                catch(Exception e){}
                currentConnection=null;
            }
        }
        return bean;
    }
}

userLogged.jsp
<%--
    Document   : userLogged
    Created on : 19 Aug, 2012, 11:50:16 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8" import="packagename.UserBean"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> User Logged Successfully</title>
    </head>
    <body>
          <table align="center">
            <%UserBean currentUser=((UserBean)(session.getAttribute("currentSessionUser")));%>              
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td><font size="3"><b>Welcome</b></font></td>
                <td><font size="3"><b><%=currentUser.getFirstName()+" "+currentUser.getLastName()%></b></font></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        <%@ include file="footer.jsp"%>
    </body>
</html>

footer.jsp
<%--
    Document   : footer
    Created on : 19 Aug, 2012, 11:50:16 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
this is my footer
</html>

Table Structure of usertable

+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| firstname  | varchar(25) | YES  |     | NULL    |       |
| lastname  | varchar(25) | YES  |     | NULL    |       |
| username | varchar(25) | YES  |     | NULL    |       |
| password | varchar(25) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

jar file needed
mysql-connector-java-3.1.14-bin








9 comments:

  1. nice explaination and i thing jsp is more useful then java m i right because i m student but my teacher says java is nothing if u dont no about of jsp the time of jsp.

    ReplyDelete
    Replies
    1. without java you cant perform any business logic with jsp..

      Delete
    2. Hi,
      In the above code..,include file="footer.jsp" is mentioned in userlogged.jsp...but there is no footer.jsp file..in the given code...!please can you exlain abou this..?

      Delete
    3. sorry..pls check the post again. i have included that file too..:)

      Delete
    4. Thank you...Mr.Aravind!..It is working with minute change in LoginServlet.java as follows...response.sendRedirect("userLogged.jsp"); changed into
      request.getRequestDispatcher("/WEB-INF/userLogged.jsp").forward(request, response);
      and the other thing is i want to display the ..Invalid User message to user.. not there in DB...can you help me out..?

      Thank you,
      Chandhrikha.

      Delete
    5. For Invalid user..in Servlet..& Error.jsp..
      request.getRequestDispatcher("/WEB-INF/Login.jsp").forward(request, response);
      }
      else{
      request.getRequestDispatcher("/WEB-INF/Error.jsp").forward(request, response);
      }
      ...Just by adding this to your code..I got what I need..Thanks a lot..:-)

      Delete
  2. how to create bean class here i'm fresher in java so that am asking

    ReplyDelete
  3. com.mysql.jdbc.Statement cannot be cast to java.beans.Statement

    Plz help me solve this problem..

    ReplyDelete
    Replies
    1. statement=(Statement)currentConnection.createStatement();

      Delete