Thursday, November 10, 2011

simple J2EE login with hibernate

In this post I’m going to show how to create simple basic login using jsp,servlat and hibernate.

                                                     First i would like to give simple description about hibernate. it's free and open source java package for object relation mapping.what that means. that mean very table at relational database map to object. for that hibernate use xml file.

                                                   Hibernate is the one of very easy way to communicate with databases in object oriented programming language.

In here first we should have to create database and tables to store data.

          CREATE TABLE IF NOT EXISTS `user_registration` (
          `index` int(11) NOT NULL AUTO_INCREMENT,
          `userName` varchar(100) NOT NULL,
          `password` varchar(100) NOT NULL,
          `email` varchar(50) NOT NULL,
           PRIMARY KEY (`index`)
           ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

 hibernate.cfg.xml - file use to setup required environment. database connection,connection pool etc.
following illustrate  hibernate.cfg.xml file for this example.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
       <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/logintest</property>
       <property name="hibernate.connection.username">root</property>
       <mapping resource="com/hibernateClass/UserRegistration.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
 

UserRegistration.hbm.xml  - use to map object with database. 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 9, 2011 6:53:58 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
  <class catalog="logintest" name="com.hibernateClass.UserRegistration" table="user_registration">
    <id name="index" type="java.lang.Integer">
      <column name="index"/>
      <generator class="identity"/>
    </id>
    <property name="userName" type="string">
      <column length="100" name="userName" not-null="true"/>
    </property>
    <property name="password" type="string">
      <column length="100" name="password" not-null="true"/>
    </property>
    <property name="email" type="string">
      <column length="50" name="email" not-null="true"/>
    </property>
  </class>
</hibernate-mapping>


<class catalog="logintest" name="com.hibernateClass.UserRegistration" table="user_registration"> is this line database table map to bean class. database is logintest class UserRegistration table name is user_registration.

    <id name="index" type="java.lang.Integer">
      <column name="index"/>
      <generator class="identity"/>
    </id>

in here map primary key to class bean. it's type is  Integer.both column name and bean name is "index".




    <property name="password" type="string">
      <column length="100" name="password" not-null="true"/>
    </property> 


this tag define an simple field in table. name is password,type is string. this type attribute demonstrate type of database field. then it map to object then veriable type should be string.
 following class illustrate bean class that map with table 


public class UserRegistration  implements java.io.Serializable {


     private Integer index;
     private String userName;
     private String password;
     private String email;

    public UserRegistration() {
    }

    public UserRegistration(String userName, String password, String email) {
       this.userName = userName;
       this.password = password;
       this.email = email;
    }
  
    public Integer getIndex() {
        return this.index;
    }
   
    public void setIndex(Integer index) {
        this.index = index;
    }
    public String getUserName() {
        return this.userName;
    }
   
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return this.password;
    }
   
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return this.email;
    }
   
    public void setEmail(String email) {
        this.email = email;
    }




}


index.jsp


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome Page</title>
    </head>
    <body>
        <h1><center><font color="RED" >User Registration </font></center></h1>
       
        <form method="POST" action="${pageContext.request.contextPath}/userRegServlet">

            <table border="0" align="center">
                <tbody>
                    <tr>
                        <td>User Name :</td>
                        <td><input type="text" name="uname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Password :</td>
                        <td><input type="password" name="pass" value="" /></td>
                    </tr>
                    <tr>
                        <td>Email : </td>
                        <td><input type="text" name="email" value="" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><input type="submit" value="Sign Up" /></td>
                    </tr>
                </tbody>
            </table>
        </form>

    </body>
    <center> <a href="login.jsp"><font color="blue">Login</font></a> </center>
</html>


before login user should have register to system.






request from this form handle by userRegServlet.java servlat.


userRegServlet.java

 package com.servlat;

import com.manager.userRegManager;
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 userRegServlet extends HttpServlet {
 
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 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");
        PrintWriter out = response.getWriter();
        try {
            String uname = (String) request.getParameter("uname");
            String pass = (String) request.getParameter("pass");
            String email = (String) request.getParameter("email");
            userRegManager insert = new userRegManager();
            insert.userInsert(uname, pass, email);
            request.setAttribute("success", uname+", successfuly register");
            response.sendRedirect("index.jsp");
         
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @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 <code>POST</code> method.
     * @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";
    }// </editor-fold>

}
in this servlat only get request parameters and it pass to manager class . in manager class we use hibernate to store data in to database.



userRegManager.java

import com.hibernateClass.UserRegistration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class userRegManager {

    /**
     * insert user registration details
     * @param uname user name
     * @param pass password
     * @param email Email address
     */
    public void userInsert(String uname, String pass, String email) {
         try {
          
            Configuration config = new Configuration().configure();
            SessionFactory factory = config.buildSessionFactory();
            Session session = factory.openSession();
            Transaction trans=session.beginTransaction();


            UserRegistration reg = new UserRegistration();
            reg.setUserName(uname);
            reg.setPassword(pass);
            reg.setEmail(email);
            session.save(reg);
            System.out.println("DONE");
            trans.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
 

 before we do anything with hibernate we should have to create hibernate session
            Configuration config = new Configuration().configure();
            SessionFactory factory = config.buildSessionFactory();
            Session session = factory.openSession();

above code segment use for create hibernate session. after that we can begin the transaction and set value that want store to transaction to bean class and save that object to session.


login.jsp


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page</title>
    </head>
    <body>
        <h1><center><font color="BLUE">LOGIN PAGE</font></center> </h1>
        <form method="POST" action="${pageContext.request.contextPath}/loginServlat">

            <table border="0" align="center">
                <thead>
                    <tr>
                        <th>User Name :</th>
                        <th><input type="text" name="uname" value="" /></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Password :</td>
                        <td><input type="password" name="pass" value="" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><input type="submit" value="Login" /></td>
                    </tr>
                </tbody>
            </table>

        </form>
    </body>
</html>







/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlat;

import com.manager.loginManager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author tharindu
 */
public class loginServlat extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 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
     */
    RequestDispatcher dispatcher;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String uname = request.getParameter("uname");
            String pass = request.getParameter("pass");

            loginManager manger = new loginManager();
            if (manger.isValidLogin(uname, pass)) {;
                request.setAttribute("uname", uname);
                dispatcher = request.getRequestDispatcher("successLogin.jsp");
                dispatcher.forward(request,response);

                response.sendRedirect("successLogin.jsp");
            } else {
                //error login
                response.sendRedirect("login.jsp");
                dispatcher = request.getRequestDispatcher("login.jsp");
                dispatcher.forward(request,response);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @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 <code>POST</code> method.
     * @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";
    }// </editor-fold>
}



login manager class 


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.manager;

import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author tharindu
 */
public class loginManager {

    private Session session;
    private int count = 0;

    public boolean isValidLogin(String uname, String pass) {

        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        session = factory.openSession();
        String query = "select reg.userName,reg.password from UserRegistration as reg where reg.userName='" + uname + "' and reg.password='" + pass + "'";
        Query DBquery = session.createQuery(query);
        for (Iterator it = DBquery.iterate(); it.hasNext();) {            it.next();
            count++;
        }
        System.out.println("Total rows: " + count);
        if (count == 1) {
            return true;
        } else {
            return false;
        }
    }
}


agian here we have create hibernate session and execute query and get data. after that you can implement your logic to check currect login is valid or not. in here myself implement simple logic to  check it.

in login servlat you can see if login success    "request.setAttribute("uname", uname)"; that mean if attribute uname is null means session not create for corrent user. only set value to uname is for valid login.

login success jsp file



<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>welcome Page</title>
        <%String uname = (String) request.getParameter("uname");
                    if (uname == null) {
                        response.sendRedirect("index.jsp");
                    }
        %>
        user name :<%=uname%>|
    <a href="logout.jsp"> Logout </a>

    </head>
    <body>

        <h1>Hello World success !</h1>
    </body>
</html>







<%String uname = (String) request.getParameter("uname");
                    if (uname == null) {
                        response.sendRedirect("index.jsp");
                    }
        %>

this code segment you can see chek if attribute uname create or not.with out create can't access this page.
if some one try to access that page with out login it redirect to index.jsp page


logout.jsp


<html>
    <head>

    </head>
    <body>
        <%
                    session.invalidate();
                    response.sendRedirect("index.jsp");
        %>
    </body>
</html>



this use to close current session and redirect to index.jsp file.



5 comments:

  1. Replies
    1. It's not working me can u share with me ur code

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks but how can I keep the user info with me in all jsp pages ?

    ReplyDelete