Menus

Jun 7, 2016

Integrating Struts2 with Hibernate

Follow steps:
1.   Create a table named users in database with following details:
CREATE TABLE `users` (
  `uname` varchar(10) NOT NULL,
  `pwd` varchar(10) default NULL,
  `email` varchar(50) default NULL,
  `dor` date default NULL,
  PRIMARY KEY  (`uname`),
  UNIQUE KEY `email` (`email`)
);
and

INSERT INTO `users` (`uname`,`pwd`,`email`,`dor`) VALUES
 ('admin','12345','test@test.com','2012-06-07');
2.   Now create a NetBeans project using hibernate framework. While creating project choose or connect to your created database.
3.   Create two packages namely  dao and entity at source packages
4.   Generate Reverse Engineering wizard at entity package
5.   Create Users.java at entity package:
package entity;
import java.util.Date;
public class Users  implements java.io.Serializable {


     private String uname;
     private String pwd;
     private String email;
     private Date dor;

    public Users() {
    }

     
    public Users(String uname) {
        this.uname = uname;
    }
    public Users(String uname, String pwd, String email, Date dor) {
       this.uname = uname;
       this.pwd = pwd;
       this.email = email;
       this.dor = dor;
    }
    
    public String getUname() {
        return this.uname;
    }
     
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPwd() {
        return this.pwd;
    }
     
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getEmail() {
        return this.email;
    }
     
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDor() {
        return this.dor;
    }
     
    public void setDor(Date dor) {
        this.dor = dor;
    }
}

6.   Create POJO at entity package:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
<hibernate-mapping>
    <class name="entity.Users" table="users" catalog="dbname" optimistic-lock="version">
        <id name="uname" type="string">
            <column name="uname" length="10" />
            <generator class="assigned" />
        </id>
        <property name="pwd" type="string">
            <column name="pwd" length="10" />
        </property>
        <property name="email" type="string">
            <column name="email" length="50" unique="true" />
        </property>
        <property name="dor" type="date">
            <column name="dor" length="10" />
        </property>
    </class>
</hibernate-mapping>
7.   Manage your 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.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"/>
    <mapping resource="entity/Login.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
8.   Create HibernateUtil.java at dao package:
package dao;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            // loads configuration and mappings
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            // builds a session factory from the service registry
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }

        return sessionFactory;
    }
}
9.   Modify the struts.xml and delete the example.xml
Struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

<struts>   
    <package name="default" extends="struts-default">
        <action name="login" class="dao.LoginAction">
            <result name="success">/hello.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>
10.               Modify the 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">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

11.               Create index.jsp at webpages:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <s:head/>
    </head>
    <body>
        <s:actionerror/>
        <s:form action="login">
            <s:textfield name="user.uname" label="Name"/>
            <s:password name="user.pwd" label="Password"/>
            <s:submit value="Login"/>
        </s:form>
    </body>
</html>

12.               Create hello.jsp at webpages:
<%@taglib uri="/struts-tags" prefix="s"%>
<b>Welcome,<s:property value="user.uname"/></b>
13.               Create LoginAction.java at package dao:
package dao;

import com.opensymphony.xwork2.ActionSupport;
import entity.Users;

public class LoginAction extends ActionSupport {

    private static final long serialVersionUID = 1L;   
    UserDao dao = new UserDao();
    Users user;

    @Override
    public void validate() {
        if (user.getUname().length() == (0)) {
            this.addFieldError("user.uname", "Name is required");
        }
        if (user.getPwd().length() == (0)) {
            this.addFieldError("user.pwd", "Password is required");
        }
    }

    @Override
    public String execute() {
        if (dao.find(user.getUname(), user.getPwd())) {
            return SUCCESS;
        } else {
            this.addActionError("Invalid username and password");
        }
        return INPUT;
    }
    

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }   
}
14.               Create UserDao.java at package dao:
package dao;

import entity.Users;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class UserDao {
    public boolean find(String name, String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        //session.beginTransaction();
        String sql = " from Users u where u.uname=:name and u.pwd=:pass";
        Query query = session.createQuery(sql);
        query.setParameter("name", name);
        query.setParameter("pass", password);
        List<Users> list = query.list();
        if (list.size() > 0) {
            session.close();
            return true;
        }
        session.close();
        return false;
    }
}
15.               Run the project in order to view the output.


No comments:

Post a Comment

Contact Form

Name

Email *

Message *