Choose Your Language

Monday 30 November 2015

restrict to copy webpage content using CSS

restricttocopy.jsp

<%--
    Document   : restricttocopy
    Created on : Nov 30, 2015, 3:51: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>
        <style>
            #restricttocopy{
            -webkit-user-select: none;  
            -moz-user-select: none;     
            -ms-user-select: none;
            user-select: none;
            }
        </style>
    </head>
    <body id="restricttocopy">
        <h1>What is android</h1>
        <p>
Android is a Linux-based open source platform for mobile cellular handsets. Android was developed by Google and the Open Handset Alliance (OHA),
a coalition of hardware, software and telecommunications companies oriented towards advancing mobile telephony standards.
 </p>
  <p>
Android platform includes an operating system based upon Linux, a GUI, a Web browser and many other
applications considered key to a modern cellular handset. Android allows synchronization to a user's address book,
calendar and other personal information management (PIM) programs, though individual software makers will have to customize their offerings.
 </p>
 <p>
Android will allow users to browse the Internet more easily, integrate mapping services with local business listings and
use many other software features traditionally associated with personal computers rather than cellphones.
        </p>
    </body>
</html>

Friday 20 November 2015

Hibernate integration for insert, update, retrive and delete records in a table using JPA Annotations

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`)
);


Users.java

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

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 *
 * @author Aravind Sankaran Nair
 */
@Entity 
@Table(name = "users", catalog = "retailer", uniqueConstraints = {@UniqueConstraint(columnNames = "uname"),@UniqueConstraint(columnNames = "upassword")})
public class Users implements Serializable {
   
    private int UID;
    private String UNAME;
    private String UPASSWORD;
    public Users(){
        
    }
    public Users(String UNAME,String UPASSWORD){        
        this.UNAME=UNAME;
        this.UPASSWORD=UPASSWORD;
    }
    public Users(int UID,String UNAME,String UPASSWORD){
        this.UID=UID;
        this.UNAME=UNAME;
        this.UPASSWORD=UPASSWORD;
    }
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "uid", nullable = false, unique = true)
    public int getUID() {
        return UID;
    }
    public void setUID(int UID) {
        this.UID = UID;
    }
    @Column(name = "uname", nullable = false, unique = true, length = 45)
    public String getUNAME() {
        return UNAME;
    }

    public void setUNAME(String UNAME) {
        this.UNAME = UNAME;
    }
    @Column(name = "upassword", nullable = false, unique = true, length = 45)
    public String getUPASSWORD() {
        return UPASSWORD;
    }

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


hibernate.cfg.xml

<?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.show_sql">true</property>
    <mapping class="hibernateannotaionexample.Users"></mapping>
  </session-factory>
</hibernate-configuration>


Operations.java

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

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

/**
 *
 * @author Aravind Sankaran Nair
 */
public class Operations {
    Session session=null;
    SessionFactory sessionFactory =new AnnotationConfiguration().configure().buildSessionFactory();
    public void insertData(String userName,String userPassword){
        session=sessionFactory.openSession();
        session.beginTransaction();
        Users user=new Users();
        user.setUNAME(userName);
        user.setUPASSWORD(userPassword);
        session.save(user);
        session.getTransaction().commit();        
    }
    
    public void updateRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="From Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
        Users u=(Users)it.next();
        u.setUNAME("meera");
        u.setUPASSWORD("sankar");
        session.update(u);
        }
        session.getTransaction().commit();
    }
    public void updateRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();       
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);
        for(Iterator it=query.iterate();it.hasNext();){
        Users u=(Users)it.next();
        
        u.setUNAME("meera");
        u.setUPASSWORD("meera");
        session.update(u);
        }
        session.getTransaction().commit();
    }
    public void showAllRecord(){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users";
        Query query=session.createQuery(SQL_QUERY);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID="+u.getUID());
            System.out.println("UNAME="+u.getUNAME());
            System.out.println("UPASSWORD="+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void showParticularRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID = "+u.getUID());
            System.out.println("UNAME = "+u.getUNAME());
            System.out.println("UPASSWORD = "+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void showParticularRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();        
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            System.out.println("UID = "+u.getUID());
            System.out.println("UNAME = "+u.getUNAME());
            System.out.println("UPASSWORD = "+u.getUPASSWORD());
        }
        session.getTransaction().commit();
    }
    public void deleteParticularRecord1(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
    public void deleteParticularRecord2(int UID){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users where UID="+UID;        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
    public void deleteALLRecord(){
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="FROM Users";        
        Query query=session.createQuery(SQL_QUERY);       
        for(Iterator it=query.iterate();it.hasNext();){
            Users u=(Users)it.next();
            session.delete(u);
        }
        session.getTransaction().commit();
    }
}


HibernateAnnotaionExample.java

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

/**
 *
 * @author Aravind Sankaran Nair
 */
public class HibernateAnnotaionExample {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Operations operations=new Operations();
        /*insert data to user table*/
        operations.insertData("aravind", "aravind");
        operations.insertData("sreeja", "damodaran");
        operations.insertData("jayesh", "babu");
        operations.insertData("bento", "rajan");
        /*update data of user table with UID value*/
        operations.updateRecord1(21);
        operations.updateRecord2(22);
        /*retrive data from user table*/
        operations.showAllRecord();
        operations.showParticularRecord1(22);
        operations.showParticularRecord2(23);
        /*delete user table records*/
        operations.deleteParticularRecord1(21);
        operations.deleteParticularRecord2(21);
        operations.deleteALLRecord();
    }
}


Jar Files Needed

hibernate
persistence
mysql-connector-java-5.1.18-bin.jar

Thursday 19 November 2015

integrating hibernate in web application for insertion, updation, selection and deletion

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 import="bean.Users"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Query"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%

    Session ses=null;
    SessionFactory sessionFactory=sessionFactory=new Configuration().configure().buildSessionFactory();
%>
<!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>
                        <table bgcolor="#819FF7">
                         
                            <tr>
                                <td>User Name</td>
                                <td>User Password</td>
                                <td>Update</td>
                            </tr>
                         
                            <%
                           
                               ses=sessionFactory.openSession();
                               String SQL_QUERY = "FROM Users users ";
                               Query query = (Query) ses.createQuery(SQL_QUERY);
                               for(Iterator it=query.iterate();it.hasNext();){
                                   Users user=(Users)it.next();%>
                                 <tr>
                                       <td><%=user.getUNAME()%></td>
                                       <td><%=user.getUPASSWORD()%></td>
                                       <td>
                                           <a href="userdetails.jsp?uid=<%=user.getUID()%>"><%=user.getUID()%></a></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>
            <table bgcolor="#BCF5A9">
                <tr>
                    <td><h1>Welcome</h1></td>
                    <td><h1><%=un%></h1></td>
                </tr>
                <tr>
                    <td><h1>User ID</h1></td>
                    <td><h1><%=id%></h1></td>
                </tr>
        
        </table>
        </center>
    </body>
</html>

userdetails.jsp

<%-- 
    Document   : userdetails
    Created on : Nov 19, 2015, 2:04:59 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page import="bean.Users"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Query"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%String uid=request.getParameter("uid");%>
<% Session ses=null;
    SessionFactory sessionFactory=sessionFactory=new Configuration().configure().buildSessionFactory();
    %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="<%=request.getContextPath()%>/Update">
                            <center>
                             <table bgcolor="#F781D8">
                            <tr>                           
                                <% 
                               ses=sessionFactory.openSession();
                               String SQL_QUERY1 = "FROM Users users where users.UID="+uid;
                               Query query1 = (Query) ses.createQuery(SQL_QUERY1);
                               for(Iterator it=query1.iterate();it.hasNext();){
                                   Users user=(Users)it.next();%>
                             
                                <td>User Name</td>
                                <td><input type="text" name="un" value="<%=user.getUNAME()%>"></td>  
                            </tr>
                            <tr>
                                <td>User Password</td>
                                <td><input type="text" name="pw" value="<%=user.getUPASSWORD()%>"></td>    
                            </tr>
                                <%} ses.flush();
                                    ses.close();
                                %>
                            
                             
                             <tr>  
                                 <td>&nbsp;<input type="hidden" name="id" value="<%=uid%>"></td>
                                 <td><input type="submit" name="update" value="Update">&nbsp;<input type="submit" name="delete" value="Delete"></td>
                                 <td>&nbsp;</td>
                             </tr>    
                        </table>
                        </center>           
                              
                            </form>
    </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>Operation failed</h1>
    </body>
</html>

Users.java

/*
 * 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

<?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

<?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>

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;

/**
 *
 * @author  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");
           
        }
    }
}

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;


/**
 *
 * @author 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");           
        }
    }
}

Update.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;

/**
 *
 * @author  Aravind Sankaran Nair
 */
public class Update extends HttpServlet {
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
        String un=request.getParameter("un");
        String pw=request.getParameter("pw");
        int id=Integer.parseInt(request.getParameter("id"));
        if(request.getParameter("update")!=null){
        Users user=new Users();
        CommonOperations commonOperations=new CommonOperations();
        user.setUID(id);
        user.setUNAME(un);
        user.setUPASSWORD(pw);
        user= commonOperations.updateUserDetails(user);
        if(user.isValid()){
            HttpSession ses=request.getSession();
            ses.setAttribute("", user);
            response.sendRedirect("index.jsp");
        }else{
            response.sendRedirect("failure.jsp");
        }
        }else  if(request.getParameter("delete")!=null){       
        
        Users user=new Users();
        CommonOperations commonOperations=new CommonOperations();
        user.setUID(id);
        user.setUNAME(un);
        user.setUPASSWORD(pw);
        user= commonOperations.removeUserDetails(user);
        if(user.isValid()){
            HttpSession ses=request.getSession();
            ses.setAttribute("", 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.flush();
        session.close();
        return user;
    }
    public Users updateUserDetails(Users user){
        int UID=user.getUID();
        String UNAME=user.getUNAME();
        String UPASSWORD=user.getUPASSWORD();
        session=sessionFactory.openSession();
        session.beginTransaction();
   
        String SQL_QUERY="FROM Users users where users.UID= :uid";
        Query query = (Query) session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);    
            user.setUNAME(UNAME);
            user.setUPASSWORD(UPASSWORD);
       
            session.update(user);
           user.setValid(true);
   
        session.getTransaction().commit();  
        session.flush();
        session.close();
        return user;
    }
    public Users removeUserDetails(Users user){
        int UID=user.getUID();
        session=sessionFactory.openSession();
        session.beginTransaction();
        String SQL_QUERY="From Users users where users.UID= :uid";
        Query query=session.createQuery(SQL_QUERY);
        query.setParameter("uid", UID);
        user.setUID(UID);
        session.delete(user);
        user.setValid(true);
       session.getTransaction().commit();  
        session.flush();
        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>
        <servlet-name>Update</servlet-name>
        <servlet-class>controller.Update</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>
    <servlet-mapping>
        <servlet-name>Update</servlet-name>
        <url-pattern>/Update</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:

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


Hibernate crud operations

Project Structure



Create database with name retailer

CREATE database retailer;

USE retailer;

CREATE TABLE  `retailer`.`customers` (
  `name` varchar(20) DEFAULT NULL,
  `C_ID` int(11) NOT NULL AUTO_INCREMENT,
  `address` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`C_ID`)
) ;

customersmapping.hbm.xml

<?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="hibernatetest.Customer" table="customers">      
  <id column="C_ID" name="customerID" type="int">
  <generator class="native"></generator>
  </id>  
  <property name="customerName">
  <column name="name"></column>
  </property>  
  <property name="customerAddress">
  <column name="address"></column>
  </property>  
  <property name="customerEmail">
  <column name="email"></column>
  </property>  
  </class> 
</hibernate-mapping>

hibernate.cfg.xml

<?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.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.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="customersmapping.hbm.xml"/>  
  </session-factory>
</hibernate-configuration>

Customer .java

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

/**
 *
 * @Aravind Sankaran Nair
 */
public class Customer {
    private String customerName;
    private int customerID;
    private String customerAddress;
    private String customerEmail;

    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }

    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    public void setCustomerID(int customerID) {
        this.customerID = customerID;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerAddress() {
        return customerAddress;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public int getCustomerID() {
        return customerID;
    }

    public String getCustomerName() {
        return customerName;
    }    
 
}

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

import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class HibernateCrud {
    Session session = null;
    SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();     
    void insertData(){
        try{
        session =sessionFactory.openSession();
        session.beginTransaction();                
        Customer customer = new Customer();
        customer.setCustomerName("Aravind");
        customer.setCustomerAddress("Trivandrum,India");
        customer.setCustomerEmail("aravind@gmail.com");  
        session.save(customer);           
        session.getTransaction().commit();       
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  } 
}
    void updateData(){         
    try{        
        session =sessionFactory.openSession();
        session.beginTransaction();    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);
        int C_ID=10;
        query.setParameter("customerId",C_ID);
        System.out.println("Reading values");
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();            
             customer.setCustomerName("updated data");
             customer.setCustomerAddress("updated data");
             customer.setCustomerEmail("updated data");
             session.update(customer);             
            }
       session.getTransaction().commit();
      
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
}
    void retriveData(){
        try{        
        session =sessionFactory.openSession();
        session.beginTransaction();
    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);
       int C_ID=10
        query.setParameter("customerId",C_ID);
       
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();
             System.out.println(customer.getCustomerName());
             System.out.println(customer.getCustomerAddress());
             System.out.println(customer.getCustomerEmail());
             System.out.println(customer.getCustomerID());        
            }
        session.getTransaction().commit();
       
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
}
    
   
    void deleteData(){
        try{
        
        session =sessionFactory.openSession();
        session.beginTransaction();
    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);  
        int C_ID=10      
        query.setParameter("customerId",C_ID);
       
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();            
             customer.setCustomerName("update");
             customer.setCustomerAddress("update");
             customer.setCustomerEmail("update");
             session.delete(customer);
            }
       session.getTransaction().commit();
        
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
    }
    public static void main(String[] args) {
       HibernateCrud hc=new HibernateCrud();
       hc.insertData();
       hc.updateData();
       hc.retriveData();
       hc.deleteData();
 }
}

Jar File Needed:

derbyclient.jar