Friday, 4 April 2014

Spring Controller with Hibernate using ContextLoaderListener

  • Below is a simple example to show how to instantiate the spring context in ContextLoaderListener and use in a HTTPServlet.
  • There are other ways of directly using Dispatcher servlet, but the is the basic way for a beginner.
  • Eclipse project for this example can be found here: spring-web-contextloader.zip
     
  • The given codebase does not contain the database scripts. You may want to create ur own tables and change the hibernate.cfg.xml and beans.xml with the database connection details
  • This code has been tested in a jetty webserver. But should work in any webserver





Web.xml -

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

    <!-- Spring app context using a listener  -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/beans.xml</param-value>
    </context-param>



    <display-name>spring-web</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Trying the simple Servlet type -->
    <servlet>
        <description></description>
        <display-name>EmployeeServlet</display-name>
        <servlet-name>EmployeeServlet</servlet-name>
        <servlet-class>org.controllers.EmployeeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>EmployeeServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app> 

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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
              http://www.springframework.org/schema/mvc 
              http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
        <property name="url" value="jdbc:hsqldb:hsql://localhost/section1" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="org.entity" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>


    <bean name="employeeDAO" class="org.dao.EmployeeDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>


hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.hsqldb.jdbc.JDBCDriver</property>
        <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost/section1</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- property name="hibernate.connection.pool_size">1</property -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>


        <!-- mapping class="org.entity.Product" / -->
        <mapping class="org.entity.Employee" />
    </session-factory>
</hibernate-configuration>


Servlet - Manual Controller

package org.controllers;

import java.io.IOException;

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

import org.dao.EmployeeDAO;
import org.entity.Employee;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class EmployeeServlet extends HttpServlet
{
    ApplicationContext ctx = null;

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException
    {
        if (ctx == null)
        {
            ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        }
        final String uri = req.getRequestURI();
        System.out.println("---------------" + uri);
        if (uri.contains("employee.action"))
        {
            getEmployee(req, resp);
        }

    }

    public void getEmployee(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException
    {
        try
        {
            final EmployeeDAO dao = ctx.getBean("employeeDAO", EmployeeDAO.class);
            final Employee emp = dao.getEmployee(null);
            req.setAttribute("emp", emp);
            req.getRequestDispatcher("employee.jsp").forward(req, resp);
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }

        req.getRequestDispatcher("errors.jsp").forward(req, resp);
    }
}


DAO

package org.dao;

import org.entity.Employee;
import org.hibernate.SessionFactory;

public class EmployeeDAO
{

    private SessionFactory sessionFactory;

    public void setSessionFactory(final SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    public Employee getEmployee(Integer id)
            throws Exception
    {
        try
        {

            if (id == null)
            {
                id = 1;
            }
            final Employee emp = (Employee) sessionFactory.openSession().get(Employee.class, id);
            System.out.println("--sessionFactory.get(Employee.class, " + id + ")   ---> " + emp);
            return emp;

        }
        catch (final Exception e)
        {
            e.printStackTrace();
            throw e;
        }
    }
}


Entity

package org.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer employeeId;
 private String firstName;
 private String lastName;
 private String jobTitle;
 private Double salary;

 public Employee() {
 }

 public Employee(Integer employeeId, String firstName, String lastName,
   String jobTitle, Double salary) {
  this.employeeId = employeeId;
  this.firstName = firstName;
  this.lastName = lastName;
  this.jobTitle = jobTitle;
  this.salary = salary;
 }
.....................
Please pick up the code from the zip file
}
 

employee.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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>Insert title here</title>
</head>
<body>
Employee : <%=request.getAttribute("emp") %>
<br/>
Employee using taglig : <c:out value="${requestScope.emp}"></c:out>
</body>
</html>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>spring-web</groupId>
    <artifactId>spring-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <!-- Spring -->
        <spring-framework.version>3.2.3.RELEASE</spring-framework.version>

        <!-- Hibernate / JPA -->
        <hibernate.version>4.2.1.Final</hibernate.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- db -->
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.2.8</version>
        </dependency>

    </dependencies>
    <build>
        ....................
        <!-- Please see attached zip containing the code --> 
    </build>
</project>
 
OUTPUT
 
 

No comments:

Post a Comment