Monday, October 8, 2012

Simple code for Ajax with Hibernate

1. Create one dynamic application in eclipse and add below jar file in class path as well in WEB-INF\lib folder:
antlr-3.1.jar
cglib-nodep-2.1_3.jar
commons-collections-3.2.jar
commons-logging-1.1.jar
dom4j-1.1.jar
hibernate-3.2.5.ga.jar
hibernate-annotations-3.4.0.GA.jar
hibernate-commons-annotations-3.3.0.ga.jar
log4j-1.2.15.jar
mysql-connector-java-3.1.12-bin.jar
persistence-api-1.0.jar
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar
transaction-api-1.1.jar

2. Create one servlet Login.java


package com.novell;

import java.io.IOException;
import java.util.List;

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;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;



public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private SessionFactory sessionFactory = null;
private Session session;
 
    public Login() {
        super();
        sessionFactory  = new AnnotationConfiguration().configure().buildSessionFactory();
       
        System.out.println("IT IS SESSION :"+session);
     }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("It is get method ..........");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
 HttpSession httpSession = request.getSession();
int userid = checkCredential(userName,password);
if(userid==0){
   httpSession.setAttribute("message", "Your Credential is wrong ........");
 RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
 rd.forward(request, response);
}else{
httpSession.setAttribute("message", "You are welcome ..........");
CalculatorState temp = getCalState(userid);
if(temp == null){
temp = new CalculatorState();
temp.setUserId(userid);
temp.setFirstValue(0);
temp.setSecondValue(0);
}
httpSession.setAttribute("state", temp);
RequestDispatcher rd = request.getRequestDispatcher("ucalc.jsp");
rd.forward(request, response);
}

}

private int checkCredential(String userName, String password){
session =sessionFactory.openSession();
List users = session.createQuery("from User where userName = '"+userName+"' and password= '"+password+"'").list();
session.close();
if(users.size()>0){return users.get(0).getId();}
else{return 0;}
}

private CalculatorState getCalState(int id){
session =sessionFactory.openSession();
List calculatorState = session.createQuery("from CalculatorState where userId = "+id).list();
System.out.println("Size of state POJO :"+calculatorState.size());
session.close();
if(calculatorState.size()==0){return null;}
else {return calculatorState.get(0);}

}

}

3. Other Servlet : Calculator.java

package com.novell;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;



public class Calculator extends HttpServlet {
private static Logger logger = Logger.getLogger(Calculator.class.getName());
private static final long serialVersionUID = 1L;
Map stragetyMap = new HashMap();
    private SessionFactory sessionFactory = null;
  private Session session;


    public Calculator() {
        super();
        sessionFactory  = new AnnotationConfiguration().configure().buildSessionFactory();
        logger.info("Servlet constructor is calling ...........");
        stragetyMap.put("add", new MainStrategy(new AddCalc()));
        stragetyMap.put("sub", new MainStrategy(new SubCalc()));
        stragetyMap.put("multi", new MainStrategy(new MultiCalc()));
        stragetyMap.put("div", new MainStrategy(new DivideCalc()));
       
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Hitting to server ............");
String first = request.getParameter("first");
String second = request.getParameter("second");
String operation = request.getParameter("operation");
String useridUI = request.getParameter("userid");
logger.info("First Number :"+first);
logger.info("Second Number :"+second);
logger.info("User id :"+useridUI);
saveLatestData(useridUI,first,second);
// int result = calculation(Integer.parseInt(first),Integer.parseInt(second),operation);
int result = ((MainStrategy)stragetyMap.get(operation)).cal(Integer.parseInt(first),Integer.parseInt(second));
saveLatestData(useridUI,first,result+"");
response.setContentType("text/html");
response.getWriter().write(result+"");
}
 
/*public int calculation(int first,int second,String operation){
MainStrategy mainStrategy = null;
if(operation.equals("add")){mainStrategy = new MainStrategy(new AddCalc());}
if(operation.equals("sub")){mainStrategy = new MainStrategy(new SubCalc());}
if(operation.equals("multi")){mainStrategy = new MainStrategy(new MultiCalc());}
if(operation.equals("div")){mainStrategy = new MainStrategy(new DivideCalc());}
return mainStrategy.cal(first, second);
}*/

private void saveLatestData(String useridUI,String first,String second){
int firstNumber  = Integer.parseInt(first);
int secondNumber = Integer.parseInt(second);
int id = Integer.parseInt(useridUI);
CalculatorState cs = new CalculatorState();
cs.setUserId(id);
cs.setFirstValue(firstNumber);
cs.setSecondValue(secondNumber);
updateCalState(cs);
}

private void updateCalState(CalculatorState cs){
try{
session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(cs);
transaction.commit();
session.flush();
   session.close();
}catch(Exception e){
e.printStackTrace();
System.out.println("Some issue while saving new data .......");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("It is Post Method ............");
doGet(request,response);
}

}


4. login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculator Login</title>
<script src="jquery.js"></script>
<script src="login.js" type="text/javascript"></script>
</head>
<body>
<h2>Please login to open your calculator</h2>
<%
 String message = (String)session.getAttribute("message");
 if(message!=null){
  out.println(message);
 }
%>
<form action="Login" method="post">
<table>
<tr><td>Please Enter User Name :</td><td><input type="text" id="userName" name="userName" /></td></tr>
<tr><td>Please Enter Password  :</td><td><input type="password" id="password" name="password"/></td></tr>
<tr><td><input type="submit" id="loginButtonSubmit" value="Submit"/></td><td><input type="button" value="Clear" id="clear"/></td></tr>
</table>
</form>
</body>
</html>


5. ucalc.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple Calculator</title>
<script type="text/javascript" src="ucal.js"></script>
<jsp:useBean id="state" class="com.novell.CalculatorState" scope="session"/>
</head>
<body>
It is simple Calculator
<br>
<input type="hidden" id="hiddenId" value="${state.userId}"/>
<input type="text" id="firstNumber" value="${state.firstValue}"/>
<input type="button" id="addButton" value="Add" onclick="addAction()"/>
<input type="text" id="secondNumber" readonly="readonly" value="${state.secondValue}"/>
<input type="button" id="clearButton" value="Clear" onclick="clearInput()"/>
</body>
</html>

6. ucal.js
var request;

function getRequest(){
      if(window.ActiveXObject){
        request = new ActiveXObject("Microsoft.XMLHTTP"); 
       }else if(window.XMLHttpRequest){
        request = new XMLHttpRequest(); 
      } 
    }

function addAction(){
 var first = document.getElementById("firstNumber").value;
 if(first==null||first==""){
alert("Please enter first number");
return null;
 }
 var second = document.getElementById("secondNumber").value;
 if(second==null||second==""){
second = 0;
 }
 var id = document.getElementById("hiddenId").value;
 //alert("Id :"+id);
 calculation(first, second, "add",id);
}

function calculation(first, second, operation,userid){
 getRequest();
 var url = "http://localhost:8080/Calculator/Calculator?first="+first+"&second="+second+"&operation="+operation+"&userid="+userid;
 //alert(url);
 request.open("POST",url,false);
 request.onreadystatechange = showResult;
 request.send();
}

function calculation2(first, second, operation){
getRequest();
var url = "http://localhost:8080/Calculator/Calculator";
     request.open("POST",url,false);
request.onreadystatechange = showResult;
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("first="+first+"&second="+second+"&operation="+operation); // Why Null
 }

function showResult(){

if(request.readyState == 4){
        var result = request.responseText;
        document.getElementById("secondNumber").value = result;
   }

}
function clearInput(){
document.getElementById("firstNumber").value="";
document.getElementById("secondNumber").value="";
}

7. User.java
package com.novell;

public class User {

private int id;
private String userName;
private String password;
 
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
 
 
}


8. CalculatorState.java
package com.novell;

public class CalculatorState {
private int userId;
private int firstValue;
private int secondValue;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getFirstValue() {
return firstValue;
}
public void setFirstValue(int firstValue) {
this.firstValue = firstValue;
}
public int getSecondValue() {
return secondValue;
}
public void setSecondValue(int secondValue) {
this.secondValue = secondValue;
}

}


9. Cal.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="com.novell.CalculatorState" table="calculator">
<id name="userId" column="id">
<generator class="assigned" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="firstValue" column="firstValue" />
<property name="secondValue" column="secondValue" />
</class>
</hibernate-mapping>


10. User.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="com.novell.User" table="login">
<id name="id" column="id">
<generator class="increment" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="userName" column="userName" />
<property name="password" column="password" />
</class>
</hibernate-mapping>


11. 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="connection.url">jdbc:mysql://localhost/sumandb</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="Cal.hbm.xml" />
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>





No comments:

Post a Comment

Please leave your feedback or your question related to this blog. :)