Using Spring Framework in Web application


Below process depicts integration of Spring Framework with the Web Project. When user access the URL the system will display message which is configured in Spring configuration file (applicationContext.xml).

Prerequisites:
1. Download spring framework libraries as shown below (spring.jar and other dependencies)
2. Application Server to deploy the application 

Project Structure (Eclipse J2EE Project template):
Testing:
- JBoss is running on 8080 port where application is deployed
http://localhost:8080/DemoHibernateSpring/hello.jsp

Output: 
Resource Reference:
(1) MessageService.java (Interface)

package control;

public interface MessageService {
   public String getMessage();
}
--------------------------------------------------------------------
(2) MessageServiceImpl.java (Implementation)


package control;

public class MessageServiceImpl implements MessageService {
private String message;
public String getMessage() {
      return this.message;
}
public void setMessage(String message) {
      this.message = message;
}
}
--------------------------------------------------------------------
(3) 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="msgService"
         class="control.MessageServiceImpl">
         <property name="message">
             <value>Hi from Spring Framework !</value>
         </property>
   </bean>
</beans>
--------------------------------------------------------------------
(4) web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
  version="2.4">
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
      <listener-class>
       org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>
</web-app>
--------------------------------------------------------------------
(5) hello.jsp

<%@ page  import="org.springframework.context.*,org.springframework.web.context.*, control.*"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% 
ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  MessageService service = (MessageService)factory.getBean("msgService");
 %>
Message : <%=service.getMessage() %>
</body>
</html>
--------------------------------------------------------------------


Using Hibernate ORM with mySQL Database

Below process depicts integration of Hibernate in J2EE Project. When user access the URL the application will insert one employee record to the Employee table and display all the records on the web page. It created new Employee table if it does not exists.

Prerequisites:
1. Download hibernate libraries as shown below (hibernate3.jar and other dependencies)
2. Create new database called "ormtest" in mySql Database (change below hibernate.cfg.xml accordingly)  (Refer -> How to install mySql and using it within Java ?)
3. Application Server to deploy the application 

Project Structure (Eclipse J2EE Project template):
Testing:
- JBoss is running on 8080 port where application is deployed
http://localhost:8080/DemoHibernate/employeeHandler.do

Output: Creates new table Employee (if already not exists) and add one record to it


Resource Reference:
(1) EmployeeHandler

package control;
import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import model.Employee;
import org.hibernate.*; 
public class EmployeeHandler extends HttpServlet {  
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                        throws IOException, ServletException{ 
      PrintWriter out = res.getWriter(); 
      //add new record
      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Employee emp = new Employee(); 
      emp.setFname("Ichiro");
      emp.setLname("Suzuki");
      session.save(emp); 
       //fetch record
      List employees = session.createQuery("from Employee").list(); 
      out.println( "Employee List size " + employees.size()); 
      for (Iterator iter = employees.iterator(); iter.hasNext(); ) { 
         Employee employee = (Employee)iter.next(); 
         out.println( employee.getFname() ); 
      }
      tx.commit();
      session.close(); 
   } 
}
--------------------------------------------------------------------
(2) HibernateUtil.java


package control;
import org.hibernate.*; 
import org.hibernate.cfg.*; 
/**
 * Utility to get handle of Hibernate session, which is require to deal with underlying Datasource
 * @author santoshlg
 *
 */
public class HibernateUtil
   private static SessionFactory sessionFactory; 
   static { 
      try { 
         sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); 
      } catch (Throwable ex) { 
         ex.printStackTrace(); 
      } 
   } 
   /**
    * Returns SessionFactory object
    * @return session
    */
   public static SessionFactory getSessionFactory() { 
      return sessionFactory; 
   }
   /**
    * Releases SessionFactory 
    */
   public static void shutdown() { 
      getSessionFactory().close(); 
   } 
}
--------------------------------------------------------------------
(3) Employee.java
package model;

/**
 * Model to hold Employee Information
 */
public class Employee {
private Long id
private String fname
private String lname;    
public Employee() {}    
/**
* @return the lname
*/
public String getLname() {
return lname;
}
/**
* @param lname the lname to set
*/
public void setLname(String lname) {
this.lname = lname;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the fname
*/
public String getFname() {
return fname;
}
/**
* @param fname the fname to set
*/
public void setFname(String fname) {
this.fname = fname;
}
}
--------------------------------------------------------------------
(4) Employee.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="model.Employee" table="Employee"> 
      <id name="id" column="EMP_ID"> 
         <generator class="native"/> 
      </id> 
      <property name="lname" column="LNAME"/> 
      <property name="fname" column="FNAME"/> 
   </class> 
</hibernate-mapping>
--------------------------------------------------------------------
(5) 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.MySQLDialect</property> 
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/ormtest</property> 
<property name="hibernate.connection.username">root</property> 
<property name="hibernate.connection.password">root</property> 
<property name="show_sql">true</property> 
<property name="hibernate.use_sql_comments">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
<property name="hibernate.hbm2ddl.auto">update</property> 
<property name="hibernate.current_session_context_class">thread</property> 
<property name="hibernate.generate_statistics">true</property> 
<property name="hibernate.format_sql">true</property>
<!-- Mapping files --> 
<mapping resource="/model/Employee.hbm.xml" /> 
</session-factory>
</hibernate-configuration>
--------------------------------------------------------------------
(6) web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app 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"
  version="2.4">
  
<servlet>
   <servlet-name>EmployeeHandler</servlet-name>
   <servlet-class>control.EmployeeHandler</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>EmployeeHandler</servlet-name>
   <url-pattern>/employeeHandler.do</url-pattern>
</servlet-mapping>
    
</web-app>
--------------------------------------------------------------------

Airline Ticket Reservation Website (Java and mySQL)


--------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------
Create 3D Animation and Video In 3 Clicks...know more

Installation and Testing of MySQL DB from Java

1. Download:
Common URL    : http://dev.mysql.com/downloads/mysql/5.1.html#downloads
MacOSX (10.6)  : http://dev.mysql.com/downloads/mirror.php?id=406393#mirrors
(mysql-5.1.61-osx10.6-x86.tar.gz)
Windows (32 bit): http://dev.mysql.com/downloads/mirror.php?id=406810#mirrors
(mysql-noinstall-5.1.61-win32.zip)
2. Install:
Unzip the zip to proper location, for example
/usr/local/mysql5
3. Configure:
i) Start mysql using below command to start it with root user
/usr/local/mysql5/bin/mysql -u root
ii) Create new Database 
mysql>CREATE DATABASE airlinedb;
iii) setup mySQL JDBC driver
a) Download JDBC Driver (Platform independent) 
b) Add mySQL jdbc driver to your project classpath 
mysql-connector-java-5.1.18-bin.jar
4.Testing:
i) Use below Java test to confirm the working   
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException; 
public class TestMySQLDB {
       public static void main(String[] argv) {
       System.out.println("Trying to connect mySQL database…");
              try { 
                     Class.forName("com.mysql.jdbc.Driver");
              } catch (ClassNotFoundException e) { 
                     System.out.println("Missing mySQL Driver?");
                     e.printStackTrace();
                     return;
              } 
              System.out.println("Registered mySQL JDBC driver successfully.");
              Connection connection = null;
              try {
                     connection = DriverManager
                                   .getConnection("jdbc:mysql://127.0.0.1:3306/airlinedb",
                                                 "root", "");

              } catch (SQLException e) {
                     System.out.println("Failed to Connect !");
                     e.printStackTrace();
                     return;
              }
               if (connection != null) {
                     System.out.println(" Connected Successfully !!!");
              } else {
                     System.out.println("Failed to Connect !");
              }
       }
}
5. Output:
Trying to connect mySQL database…

Registered mySQL JDBC driver successfully.
 Connected Successfully !!!

Airline Ticket Reservation Sample Website

1) Introduction:
Airline Ticket Reservation is a sample web application which could be use to search flights based on the specified airports (departure airport, arrival airport) and dates (departure date and return date).
2) References: 
- For basic DB preparations please refer to notes titled "Installation and Testing of Hypersonic DB"
- For basic Java EE setup for Airline Ticket Reservation Project refer to notes titled "Build and Deployment of Java EE Web Application (Airline Ticket Reservation)"
3) Database Preparations:
Create 2 tables as shown below:
i) Table to store Sector information as described below

CREATE TABLE SECTOR (
DEPARTURE_AP VARCHAR(100),
ARRIVAL_AP VARCHAR(100),
DEPARTURE_DT DATE,
ARRIVAL_DT DATE,
DEPARTURE_TM DECIMAL(4,2),
ARRIVAL_TM DECIMAL(4,2) ,
SID INTEGER,
PID INTEGER,
PRIMARY KEY (SID)
)
Insert 4 sample records: 
INSERT INTO SECTOR (DEPARTURE_AP, ARRIVAL_AP, DEPARTURE_DT,ARRIVAL_DT, DEPARTURE_TM, ARRIVAL_TM, SID, PID ) values ('NRT','LAX',DATE '2012-05-15',DATE '2012-05-15',10.05,19.01,1, 1)
INSERT INTO SECTOR (DEPARTURE_AP, ARRIVAL_AP, DEPARTURE_DT,ARRIVAL_DT, DEPARTURE_TM, ARRIVAL_TM, SID, PID ) values ('NRT','LAX',DATE '2012-05-15',DATE '2012-05-16',23.00,06.15,2, 2) 
INSERT INTO SECTOR (DEPARTURE_AP, ARRIVAL_AP, DEPARTURE_DT,ARRIVAL_DT, DEPARTURE_TM, ARRIVAL_TM, SID, PID ) values ('LAX','NRT',DATE '2012-05-25',DATE '2012-05-25',12.05,21.00,3, 1)
INSERT INTO SECTOR (DEPARTURE_AP, ARRIVAL_AP, DEPARTURE_DT,ARRIVAL_DT, DEPARTURE_TM, ARRIVAL_TM, SID, PID ) values ('LAX','NRT',DATE '2012-05-27',DATE '2012-05-27',11.05,20.00,4, 2)

ii) Table to store Price information as described below

CREATE TABLE PRICE (
PID INTEGER,
BASIC DECIMAL(10,2),
SURCHARGE DECIMAL(10,2),
TAX DECIMAL(10,2),
DISCOUNT DECIMAL(10,2),
CURR VARCHAR(3),
PRIMARY KEY (PID)
)
Insert 2 sample records: 

INSERT INTO PRICE (PID,BASIC,SURCHARGE,TAX,DISCOUNT,CURR) VALUES (1,1200,110,50,75,'USD')
INSERT INTO PRICE (PID,BASIC,SURCHARGE,TAX,DISCOUNT,CURR) VALUES (2,1800,200,145,105,'USD')









4) Java Source Preparations:
- Add hsqldb.jar to [/WEB-INF/lib] of "AirlineTicketReservation" Project in Eclipse

Installation and Testing of Hypersonic DB from Java

1. Download:
http://sourceforge.net/projects/hsqldb/files/hsqldb/hsqldb_2_2/hsqldb-2.2.8.zip/download
2. Install:
Unzip the hsqldb-2.2.8.zip to proper location, for example
/usr/local/hsqldb
3. Configure:
i) Open Configuration GUI using below command,
/usr/local/hsqldb/lib/java -jar hsqldb.jar
ii) Provide location for file based database, for example 
/Users/santoshlg/testdb

iii) To use hsqldb from the Eclipse project, add hsqldb.jar in the Eclipse Project Library reference,
4.Testing:
i) Connect to db GUI Console using above configuration to get below Database Manager GUI
ii) Create sample table CUSTOMER by using GUI Editor 
(Editor appears after successful connection as per above step i) 
CREATE TABLE CUSTOMER (
            LAST_NAME VARCHAR(60),
            FIRST_NAME VARCHAR(60),
            ACCOUNT_ID VARCHAR(10)
)

iii) Insert 2 test records
INSERT INTO CUSTOMER
            (LAST_NAME, FIRST_NAME,ACCOUNT_ID)
            VALUES
            ('HONDA','YUKI','A-1001');
INSERT INTO CUSTOMER
            (LAST_NAME, FIRST_NAME,ACCOUNT_ID)
            VALUES
            ('SUZUKI','ICHIRO','A-1002');

iv) Use below Java test to confirm the working 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestHSQLDB {
public static void main(String[] args) throws SQLException {
 
Connection conn = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
 
 try {
  Class.forName("org.hsqldb.jdbc.JDBCDriver");
  conn = 
  DriverManager.getConnection("jdbc:hsqldb:file:/Users/santoshlg/testdb", "SA", "");

            String selectStatement =
                "select * from Customer where ACCOUNT_ID = ?";
            prepStmt = conn.prepareStatement(selectStatement);
            prepStmt.setString(1, "A-1001");
            rs = prepStmt.executeQuery();

            while (rs.next()) {
                String title = rs.getString("LAST_NAME");
                System.out.println(title);
            }

  } catch (Exception e) {
      System.err.println("ERROR: failed to load HSQLDB JDBC driver.");
      e.printStackTrace();
  } finally {
            rs.close();
            prepStmt.close();
  conn.close();
  }
}
}

5. Output:
HONDA