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!

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, October 7, 2013

HelloWorld - a Web application based on Spring framework

Objective
We will learn how to create a simple Web application with Spring framework with Eclipse. The Web application has two JSP pages:
- hello.jsp: It displays a welcome phrase to Spring framework!

Web application creation with Eclipse
  - Step 1: start the Eclipse J2EE environment, click on New project -> Dynamic Web project



- Step 2: type the project name as spring-helloworld, then click Finish

- Step 3: create folders, files in project directory as follow:
 - in the src folder, create a package control. In the package control, create a java class of name HelloControl.
 - in the WebContent folder, create a JSP page: hello.jsp.
- in the WebContent/WEB-INF/ folder, create two files: web.xml and spring-helloworld-servlet.xml



 - Step 4: Download all Spring library files (from: http://sourceforge.net/projects/springframework/) and then add them into the WebContent/WEB-INF/lib folder:



 - Step 5: define all java classes, jsp files and .xml files

 HelloControl.java
 package control;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;

@Controller
public class HelloControl{

   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String printHello(ModelMap model) {
      model.addAttribute("message", "Hello Spring MVC Web Framework!");

      return "hello";
   }
}

 hello.jsp
 <%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h2>${message}</h2>
</body>
</html>

 web.xml
 <web-app id="WebApp_ID" 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>Spring MVC Web Application</display-name>
   <servlet>
      <servlet-name>spring-helloworld</servlet-name>
      <servlet-class>  org.springframework.web.servlet.DispatcherServlet </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-helloworld-servlet.xml</param-value>
        </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring-helloworld</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping> 
</web-app>

spring-helloworld-servlet.xml
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans    
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="control" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
   </bean>
</beans>

 Results

 

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: