Pages

Tuesday, June 5, 2012

Spring Hibernate sample application

Spring Hibernate Integration Login Example using MySQL database and Tomcat Web Server.
A short description of how Spring MVC works (source : http://www.javacodegeeks.com)
When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The “DispatcherServlet” first receives the request
  • The “DispatcherServlet” consults the “HandlerMapping” and invokes the "Controller" associated with the request
  • The "Controller" process the request by calling the appropriate service methods and returns a “ModeAndView” object to the “DispatcherServlet”. The “ModeAndView” object contains the model data and the view name
  • The “DispatcherServlet” sends the view name to a “ViewResolver” to find the actual “View” to invoke
  • The “DispatcherServlet” passes the model object to the “View” to render the result
  • The “View” with the help of the model data renders the result and return it back to the user 
Eg : Employee Login:
First create a table called 'loginbean' and insert some values.

create table loginbean( empid int(10) not null primary key, name varchar(50) not null, desk_extn int(4), password varchar(15) not null );
insert into loginbean values(12345,'S L N V Praveen',1234,'praveen');
The directory structure as follows (Eclipse IDE)
Add the required jar files to the build path and WEB-INF/lib folder from spring/hibernate framework.
Java build path:
WEB-INF/lib:
Now create a bean called LoginBean
LginBean.java
package com.shlogin.sample;

public class LoginBean {
 
 private Integer empId;
 private String empName;
 private int deskExtn;
 private String password;
  
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getDeskExtn() {
  return deskExtn;
 }
 public void setDeskExtn(int deskExtn) {
  this.deskExtn = deskExtn;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public Integer getEmpId() {
  return empId;
 }
 public void setEmpId(Integer empId) {
  this.empId = empId;
 }
}
Now define the hbm file.
LoginBean.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.shlogin.sample.LoginBean" table="loginbean">
  <id name="empId" column="empid" type="int">
   <generator class="assigned" />
  </id>
  <property name="empName" column="name" type="string" />
  <property name="deskExtn" column="desk_extn" type="int" />
  <property name="password" column="password" type="string" />
 </class>
</hibernate-mapping>

Other source files
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <display-name>springhibernate</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
 </context-param>
 <servlet>
   <servlet-name>context</servlet-name>
   <servlet-class>
   org.springframework.web.context.ContextLoaderServlet
   </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
    <!-- Spring context loading ends-->
  <servlet>
  <servlet-name>login</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 <taglib>
  <taglib-uri>/spring</taglib-uri>
  <taglib-location>/WEB-INF/spring.tld</taglib-location>
 </taglib>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

login-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> 
    <bean id="loginFormValidator" class="com.shlogin.sample.LoginFormValidator"/>    
    <bean id="loginController" class="com.shlogin.sample.LoginController">
     <property name="sessionForm"><value>true</value></property>        
      <property name="commandName"><value>loginBean</value></property> 
      <property name="commandClass"><value>com.shlogin.sample.LoginBean</value></property>   
      <property name="validator"><ref bean="loginFormValidator"/></property>
      <property name="formView"><value>login</value></property>
      <property name="successView"><value>success</value></property>
      <property name="failureView"><value>failure</value></property>
      <property name="logindao"><ref bean="logindao"/></property>
    </bean>  
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
      <property name="urlMap">
         <map>
            <entry key="/login/loginPage.do"><ref bean="loginController"/></entry>
         </map>
      </property>
   </bean>    
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
        <property name="prefix"><value>/WEB-INF/jsp/</value></property>
        <property name="suffix"><value>.jsp</value></property>
   </bean>        
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
 <bean id="myDataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName">
   <value>com.mysql.jdbc.Driver</value>
  </property>
  <property name="url">
   <value>jdbc:mysql://localhost:3306/user</value>
  </property>
  <property name="username">
   <value>root</value>
  </property>
  <property name="password">
   <value></value>
  </property>
 </bean>
 <bean id="mySessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
   <ref bean="myDataSource" />
  </property>
  <property name="mappingResources">
   <list>
    <value>/com/shlogin/sample/LoginBean.hbm.xml</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">
     org.hibernate.dialect.MySQLDialect
    </prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>
 <bean id="logindao" class="com.shlogin.sample.LoginDAO">
  <property name="sessionFactory">
   <ref bean="mySessionFactory" />
  </property>
 </bean>
</beans>
login.jsp
<%@ taglib prefix="core" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head><title>Spring Hibernate Example</title></head>
<body>
<center>
 <h1>Login Page</h1>
 <br/> 
 <form method="post" action="/springHibernateLogin/login/loginPage.do">
  <table width="70%" border="1">
   <tr>
    <td align="center" bgcolor="lightblue">Employee Login</td>
   </tr>
   <tr>
    <td>
     <table border="0" width="100%">
      <tr>
       <td width="33%" align="right">EmpId: </td>
       <td width="66%" align="left">
        <spring:bind path="loginBean.empId">
        <input type="text" 
               name="empId" 
               value="<core:out value="${status.value}"/>"/>  
        </spring:bind>
       </td>       
      </tr>
      <tr>
       <td colspan="2" align="center">
        <spring:hasBindErrors name="loginBean">
        <font color="red"><core:out value="${status.errorMessage}"/></font>
        </spring:hasBindErrors>
       </td>
      </tr>
      <tr>
       <td width="33%" align="right">Password: </td>
       <td width="66%" align="left">
        <spring:bind path="loginBean.password">
        <input type="password" name="password" />
        </spring:bind>
       </td>
      </tr>
      <tr>
       <td colspan="2" align="center">
        <spring:hasBindErrors name="loginBean">
        <font color="red"><core:out value="${status.errorMessage}"/></font>
        </spring:hasBindErrors>
       </td>
      </tr>
      <tr>
       <td align="center" colspan="2">
        <input type="submit" align="middle" value="Login">
       </td>
      </tr>
     </table>
     
    </td>
   </tr>
  </table>  
 </form>
</center>
</body>
</html>
failure.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>Failed</title>
</head>
<body>
<h3>Failed to Login...!!!</h3>
<a href="/springHibernateLogin/login/loginPage.do"><h4>Back</h4></a>
</body>
</html>
success.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">
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>success</title>
<script language="javascript" type="text/javascript">
window.history.forward(1);
</script>
</head>
<body>
<form action="/springHibernateLogin/login/loginPage.do">
<h3>Hello...<c:out value="${name}" /></h3>
<input type="submit" value="Logout" /></form>
</body>
</html>
LoginController.java
package com.shlogin.sample;

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

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

@Controller
public class LoginController extends SimpleFormController {
 private LoginDAO logindao;
 private String failureView; 
 public Object formBackingObject(HttpServletRequest request) throws ServletException
 {
  LoginBean backingObject = new LoginBean();
  System.out.println("formBackingObject");
  return backingObject;
 }
 
 public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)  throws ServletException
 {
  LoginBean user = (LoginBean)command;
  System.out.println("user name : " user.getEmpId());
  System.out.println("dept name : " user.getPassword());
  boolean result = getLogindao().checkUser(user);
  System.out.println("result = " result);
  if(result)
  {   
   request.setAttribute("name", getLogindao().getUser());
   return new ModelAndView("success");
  }
  else
   return new ModelAndView("failure");
 } 
 // returns the logindao
 public LoginDAO getLogindao()
 {
  return logindao;
 }
 
 public void setLogindao(LoginDAO logindao)
 {
  this.logindao = logindao;
 }  

 public final void setFailureView(String failureView)
 {
  this.failureView = failureView;
 }
 
 protected final String getFailureView()
 {
 return (failureView);
 }
}
LoginDAO.java
package com.shlogin.sample;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class LoginDAO { 
 private SessionFactory sessionFactory;
 String name = "";
  
 public void setUser(String name)
 {
  this.name = name;  
 }
 
 public String getUser()
 {
  return name;  
 }
 
 public boolean checkUser(LoginBean loginBean)
 {
  System.out.println("in checkUser method");
  Session session = getSessionFactory().openSession();
  System.out.println(session);
  boolean result = false;
  try
  {  
   String SQL_QUERY ="from LoginBean loginbean where empid = ? and password = ?";
     Query query = session.createQuery(SQL_QUERY);
     query.setInteger(0, loginBean.getEmpId());
     query.setString(1, loginBean.getPassword());
     for(Iterator it=query.iterate();it.hasNext();){
      LoginBean loginbean=(LoginBean)it.next();
      System.out.println("ID: "   loginBean.getEmpId());
      name = loginbean.getEmpName();
      System.out.println("FirstName: "   name);
      setUser(name);    
      result = true;
    }   
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  return result;
 }
 
 /*
  * returns the sessionFactory
  */
 public SessionFactory getSessionFactory()
 {
  return sessionFactory;
 }
 
 public void setSessionFactory(SessionFactory sessionFactory)
 {
  this.sessionFactory = sessionFactory;
 }
}
LoginFormValidator.java
package com.shlogin.sample;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class LoginFormValidator implements Validator{
  public boolean supports(Class clazz) {
        return clazz.equals(LoginBean.class);
    }
  
  public void validate(Object obj, Errors errors) {
   LoginBean user = (LoginBean) obj;
        if (user.getEmpId()== null && user.getPassword().trim().length() <= 0) {
         System.out.println("EmpId and Password fields required");
            errors.rejectValue("empId", "error.login.not-specified", null,"Value required");
        } else {  
         System.out.println("user obj : " user);
         System.out.println(user.getEmpId());
            if (user.getEmpId()== null) {
             System.out.println("EmpId null value");
                errors.rejectValue("empId", "error.login.invalid-user",
                        null, "Employee Id Required");
            } 
            if (user.getPassword().trim().length() <= 0) {
             System.out.println("Password null value");
                    errors.rejectValue("password", "error.login.invalid-dept",
                            null, "Password is Required");
                }    
        }
    }
}
 
 
On running the above application:
 on successful login :
Happy coding...!!!

No comments:

Post a Comment