Choose Your Language

Wednesday 18 November 2015

login and registration using hibernate, mysql, jsp, servlets and netbeans


Project Structure



Create a database with name retailer 

create database retailer;
use retailer;

Create a table with name users

DROP TABLE IF EXISTS `retailer`.`users`;
CREATE TABLE  `retailer`.`users` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uname` varchar(45) DEFAULT NULL,
  `upassword` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`uid`)
);

index.jsp

<%--
    Document   : index
    Created on : Nov 18, 2015, 4:04:04 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
    <center>
        <table>
            <tr>
                <td>Login</td>
                <td>Registration</td>
            </tr>
            <tr>
                <td>
                    <table bgcolor="yellow">
                        <form method="post" action="<%=request.getContextPath()%>/Login">
                        <tr>
                            <td>User Name </td>
                            <td><input type="text" name="un"></td>
                        </tr>
                         <tr>
                            <td>Password </td>
                            <td><input type="text" name="pw"></td>
                        </tr>
                         <tr>
                            <td></td>
                            <td><input type="submit" value="login"></td>
                        </tr>
                         </form>
                    </table>
                </td>
                <td>
                     <table bgcolor="red">
                        <form method="post" action="<%=request.getContextPath()%>/Register">
                        <tr>
                            <td>User Name </td>
                            <td><input type="text" name="un"></td>
                        </tr>
                         <tr>
                            <td>Password </td>
                            <td><input type="text" name="pw"></td>
                        </tr>
                         <tr>
                            <td></td>
                            <td><input type="submit" value="Register"></td>
                        </tr>
                         </form>
                    </table>
                </td>
            </tr>
        </table>
    </center>      
    </body>
</html>

userhome.jsp

<%-- 
    Document   : userhome
    Created on : Nov 19, 2015, 11:59:22 AM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% String id=request.getParameter("id");
String un=request.getParameter("uname");
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <center>
        <h1>Welcome <%=un%></h1>
        <h1>Your ID is <%=id%></h1>
        </center>
    </body>
</html>

failure.jsp

<%-- 
    Document   : failure
    Created on : Nov 19, 2015, 12:23:55 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Insertion failed</h1>
    </body>
</html>

Users.java (Bean Class)

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

/**
 *
 * @author Aravind Sankaran Nair
 */
public class Users {
   private int UID;
   private String UNAME; 
   private String UPASSWORD;
boolean valid;

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }
    public int getUID() {
        return UID;
    }

    public void setUID(int UID) {
        this.UID = UID;
    }

    public String getUNAME() {
        return UNAME;
    }

    public void setUNAME(String UNAME) {
        this.UNAME = UNAME;
    }

    public String getUPASSWORD() {
        return UPASSWORD;
    }

    public void setUPASSWORD(String UPASSWORD) {
        this.UPASSWORD = UPASSWORD;
    }
}

hibernate.cfg.xml (hibernate configuration file)

<?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/retailer</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="usermapping.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

usermapping.hbm.xml (hibernate mapping file)

<?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">
<hibernate-mapping>
  <class name="bean.Users" table="users">
      <id name="UID" column="uid" type="int">
          <generator class="native"></generator>
      </id>
      <property name="UNAME">
          <column name="uname"></column>
      </property>
      <property name="UPASSWORD">
          <column name="upassword"></column>
      </property>
  </class>
</hibernate-mapping>

Login.java (Servlet)

package controller;

import bean.Users;
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;
import javax.servlet.http.HttpSession;
import operations.CommonOperations;
/**
 *
 * @Aravind Sankaran Nair
 */
public class Login extends HttpServlet {
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String un=request.getParameter("un");
        String pw=request.getParameter("pw");
     
        Users user=new Users();
        CommonOperations co=new CommonOperations();
        user.setUNAME(un);
        user.setUPASSWORD(pw);
        
        user=co.getLoginDetails(user);
        if(user.isValid()){
            HttpSession session=request.getSession();
            session.setAttribute("currentsession", user);
            response.sendRedirect("userhome.jsp?id="+user.getUID()+"&uname="+user.getUNAME());
        }else{
            response.sendRedirect("index.jsp");           
        }
    }
}

Register.java (Servlet)

package controller;

import bean.Users;
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;
import javax.servlet.http.HttpSession;
import operations.CommonOperations;

/**
 *
 * @Aravind Sankaran Nair
 */
public class Register extends HttpServlet {
 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String un=request.getParameter("un");
       String pw=request.getParameter("pw");
        Users user=new Users();
        user.setUNAME(un);
        user.setUPASSWORD(pw);
        CommonOperations commonOperations=new CommonOperations();
        user=commonOperations.registerUser(user);
        if(user.isValid()){
            HttpSession session=request.getSession();
            session.setAttribute("currentsession", user);
            response.sendRedirect("index.jsp");
        }else{
            response.sendRedirect("failure.jsp");
           
        }
    }
}

CommonOperations.java 

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

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


/**
 *
 * @author Aravind Sankaran Nair
 */
public class CommonOperations {
    Session session=null;
    SessionFactory sessionFactory=sessionFactory=new Configuration().configure().buildSessionFactory(); 
     public Users getLoginDetails(Users user){
         session=sessionFactory.openSession();
         session.beginTransaction();
         String UNAME=user.getUNAME();
         String UPASSWORD=user.getUPASSWORD();
         String SQL_QUERY = "FROM Users users WHERE users.UNAME = '"+UNAME+"' AND users.UPASSWORD= '"+UPASSWORD+"'";         
         Query query = (Query) session.createQuery(SQL_QUERY);        
            for(Iterator it=query.iterate();it.hasNext();)  
            {  
            Users u = (Users)it.next();  
            user.setUID(u.getUID());
            user.setUNAME(u.getUNAME());
            user.setUPASSWORD(u.getUPASSWORD()); 
            user.setValid(true);
            }  
         session.getTransaction().commit();     
         session.close();  
    return user;   
    }
    public Users registerUser(Users user){
        session=sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        user.setValid(true);
        session.getTransaction().commit();
        session.close();
        return user;
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>controller.Login</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Register</servlet-name>
        <servlet-class>controller.Register</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Register</servlet-name>
        <url-pattern>/Register</url-pattern>
    </servlet-mapping>
   
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Jar Needed:

Hibernate 3.2.5
ejb3-persistence.jar
derbyclient.jar
mysql-connector-java-5.1.18-bin.jar

Output


5 comments: