Dears,

This blog is moved to a new blog at:

The new update will be found at that new blog, please follow it!
This blog is no more updated.
Thanks for your visit!

Monday, October 7, 2013

Web application based on Struts 2 using Hibernate

Objective
We will create a Web application of login based on Struts 2 framework in Eclipse:
- a login page enabling to enter username/password, a submit button
- when the submit button is clicked, the server receives the username/password and verifies it from the DB on the server (using Hibernate).
- if the login is success, a success page will appear
- otherwise, a failure page is displayed.

 Project development
 Create a project (to see how to create a Web project and download Struts 2 library, please see: http://coderandcode.blogspot.com/2013/10/helloworld-simple-web-application-with.html) with folders and files in the project directory as follow:
- in the src folder, create two packages: control and model. In package control, create two java classes of name LoginAction and HibernateUser. In package model, create a java class of name User.
- add a resource folder into project directory and create files: ApplicationResources.properties, hibernate.cfg.xml, user.hbm.xml
- in the WebContent folder, create two JSP pages: login and success.
- in the WebContent/WEB-INF/ folder, create a file web.xml
- in the WebContent/WEB-INF/classes folder, create a file struts.xml

 

 - On the database level, create a database named "hotelmanagement" which contains a table users as follow:



 We now have to define all java classes, jsp pages, .properties and .xml file

User.java (A POJO class)
package model;
import java.io.Serializable;

public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String password;
    private String fullName;
    private String idCardNumber;
    private String idCardType;
    private String address;
    private String description;
   
    public User(){       
    }
   
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
   
    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getIdCardNumber() {
        return idCardNumber;
    }

    public void setIdCardNumber(String idCardNumber) {
        this.idCardNumber = idCardNumber;
    }

    public String getIdCardType() {
        return idCardType;
    }

    public void setIdCardType(String idCardType) {
        this.idCardType = idCardType;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDescription() {
        return description;
    }


    public void setDescription(String description) {
        this.description = description;
    }

    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;
    }   
}

 HibernateUser.java
 package control;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import model.User;

public class HibernateUser{
    private static final SessionFactory sessionFactory = buildSessionFactory();
    
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
  
    public boolean checkLogin(User user){
        boolean result = false;
        Session session = this.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<User> users = null;
        String sql = "FROM User U WHERE U.username = :username AND U.password = :password";
        try {
            Query q =  session.createQuery(sql);
            q.setParameter("username", user.getUsername());
            q.setParameter("password", user.getPassword());
            users = (List<User>)q.list();
            if (users.size() > 0) result = true;
           
        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        session.getTransaction().commit();
        return result;
    }
}

 LoginAction.java
 package control;
import model.User;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
    private static final long serialVersionUID = 2L;    
    private User userBean;
  
    public String execute() throws Exception {
        HibernateUser hu = new HibernateUser();
        if (hu.checkLogin(userBean)) {
            return "success";
        } else {
            addActionError(getText("error.login"));
            return "input";
        }
    }
   
    public void validate(){
        //The addFieldError method takes two arguments.
        //The first is the form field name to which the error applies
        //and the second is the error message to display above that form field.
        if ( userBean.getUsername().length() == 0 ){
            addFieldError( "userBean.username", "Username is required." );
        }
               
        if ( userBean.getPassword().length() == 0 ){
            addFieldError( "userBean.password", "Password is required." );
        }
    }

    public User getUserBean() {
        return userBean;
    }

    public void setUserBean(User userBean) {
        this.userBean = userBean;
    }   
}

 ApplicationResources.properties
 label.username= Username
label.password= Password
label.login= Login
error.login = Username and password incorrect! Try again...

 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.driver_class"> com.mysql.jdbc.Driver </property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hotelmanagement </property>
        <property name="connection.username">root</property>
        <property name="connection.password">12345678</property>
        <property name="connection.pool_size">1</property>
        <property name="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="hbm2ddl.auto">update</property>

        <mapping resource="user.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 user.hbm.xml
 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="model.User" table="tbluser" >
  <id name="id" type="int" column="id" >   <generator class="native"/>  </id>

  <property name="username">   <column name="username" />  </property>
  <property name="password">   <column name="password"/>  </property>
  <property name="fullName">   <column name="fullName" />  </property>
  <property name="idCardNumber">   <column name="idCardNumber"/>  </property>
  <property name="idCardType">   <column name="idCardType" />  </property>
  <property name="address">   <column name="address"/>  </property>
  <property name="description">   <column name="description" />  </property>
 </class>
</hibernate-mapping>

 login.jsp
 <%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application</title>
</head>

<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="login" method="post">
    <s:textfield name="userBean.username" key="label.username" size="20" />
    <s:password name="userBean.password" key="label.password" size="20" />
    <s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

 success.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>

<body>
    <h2>Hi, <s:property value="userBean.username" />!</h2>
</body>
</html>

 web.xml
 <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

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

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 struts.xml
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <constant name="struts.devMode" value="true" />
  <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
  <package name="basicstruts2" extends="struts-default">

  <action name="index">
    <result>/login.jsp</result>
  </action>
      
  <action name="login" class="control.LoginAction" method="execute">
    <result name="success">/success.jsp</result>
    <result name="input">/login.jsp</result>
  </action>
</package>
</struts>

 Results
 - login page:



 - success page:


4 comments:

  1. hello plz what are the jars that we will need cauze i have the 404 problem resource not available

    ReplyDelete
    Replies
    1. common-logging.jar, freemarker.jar, xwork.jar, ognl.jar & struts-2-core.jar are need for this project @ anrani

      Delete
  2. Hi, for me it shows following error

    ReplyDelete
  3. Hi, for me it shows following error

    ReplyDelete