Spring MVC Tutorial

Spring and Hibernate Integration Example Using Eclipse Maven

This tutorial shows you how to run a simple spring hibernate example and develop a registration and login example.

Environment used

  •     Eclipse EE
  •     Maven 4
  •     Spring 4.2
  •     Hibernate 4
  •     Mysql 5+
  •     JDK 8

Spring hibernate maven dependency

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.candidjava.spring</groupId>
  <artifactId>springhibernatexml</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springhibernatexml</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.1.0.Final</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.36</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <downloadJavadocs>false</downloadJavadocs>
          <wtpversion>2.0</wtpversion>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
          <webResources>
            <resource>
              <directory>${project.build.sourceDirectory}</directory>
              <targetPath>WEB-INF/classes</targetPath>
            </resource>
          </webResources>
        </configuration>
      </plugin>
    </plugins>
    <finalName>springhibernate</finalName>
  </build>
</project>

Create a simple index page to redirect to spring controller

<%
  response.sendRedirect("login");
%>

Spring hibernate configuration code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

  <context:component-scan base-package="com.candidjava.springmvc.controller" />

  <context:property-placeholder location="classpath:database.properties" />

  <mvc:annotation-driven />
  
  <bean id="dataSource111" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.user}" />
    <property name="password" value="${database.password}" />
  </bean>
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    
    <property name="dataSource" ref="dataSource111" />
    
    <property name="annotatedClasses">
      <list>
        <value>com.candidjava.springmvc.entity.Employee</value>
        
      </list>
    </property>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
      </props>
    </property>
  </bean>
  
  <tx:annotation-driven/> 
  
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>
  
  <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
  
  <bean id="jspViewResolver" 	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" 	value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
  </bean>
  
  <bean id="employeeDao" class="com.candidjava.springmvc.dao.impl.EmployeeDAOImpl" />
  <bean id="employeeService" class="com.candidjava.springmvc.service.impl.EmployeeServiceImpl" />
</beans>

Spring Controller class

package com.candidjava.springmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.springmvc.entity.Employee;
import com.candidjava.springmvc.service.EmployeeService;

@Controller
public class EmployeeController {

  @Autowired
  private EmployeeService employeeService;

  @RequestMapping(value = "register", method = RequestMethod.GET)
  public ModelAndView viewRegister(@ModelAttribute Employee employee) {
    return new ModelAndView("register");
  }

  @RequestMapping(value = "register", method = RequestMethod.POST)
  public ModelAndView createUser(@ModelAttribute Employee employee) {
    employeeService.createEmployee(employee);
    return new ModelAndView("login");
  }

  @RequestMapping(value = "login", method = RequestMethod.GET)
  public ModelAndView viewLogin(@ModelAttribute Employee employee) {
    return new ModelAndView("login");
  }

  @RequestMapping(value = "login", method = RequestMethod.POST)
  public ModelAndView processLogin(@ModelAttribute Employee employee) {
    Employee emp = employeeService.getEmployee(employee);
    ModelAndView model = null;
    if (emp == null) {
      model = new ModelAndView("login");
      model.addObject("result", "Invalid Username or Password");
    } else {
      model = new ModelAndView("home");
      model.addObject("emp", emp.getName());
    }
    return model;
  }

}

Spring login page

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
  color: #FF0000
}
-->
</style>
</head>
<body>
  <form:form id="form1" name="form1" modelAttribute="employee" method="post" action="login">
    <table width="526" border="0" align="center">
      <tr>
        <td width="520">&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td><fieldset>
            <legend>Login</legend>
            <table width="499" border="0" align="center">
              <tr>
                <td colspan="5">&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td colspan="3" style="color: red"><c:if
                    test="${not empty result}">${result}</c:if></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td width="50">&nbsp;</td>
                <td width="114">Username</td>
                <td colspan="2"><label> 
<form:input type="text"	name="txt_username" id="txt_username" style=" width : 159px;" path="username" />
                </label></td>
                <td width="131">&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>Password</td>
                <td colspan="2"><label> 
<form:input type="password" name="txt_password" id="txt_password" style=" width : 160px;" path="password" />
                </label></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td width="109"><label></label></td>
                <td width="73"><label> 
<input type="submit" name="btn_login" id="btn_login" value="Login" />
                </label></td>
                <td><a href="register">Register Here >>></a></td>
              </tr>
            </table>
          </fieldset></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

Spring registration page design

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
  <form:form id="form1" name="form1" modelAttribute="employee" method="post" action="register">
    <table width="200" border="0" align="center">
      <tr>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td><fieldset>
            <legend>Register</legend>
            <table width="609" border="0" align="center">

              <tr>
                <td width="69">&nbsp;</td>
                <td colspan="2">Username</td>
                <td colspan="3"><label> <form:input type="text"
                      name="txt_username" id="txt_username" path="username" />
                </label></td>
                <td width="56">&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td colspan="2">Password</td>
                <td colspan="3"><form:input type="password"
                    name="txt_password" id="txt_password" path="password" /></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td colspan="2">Name</td>
                <td colspan="3"><form:input type="text" name="txt_name"
                    id="txt_name" path="name" /></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td colspan="2">Email</td>
                <td colspan="3"><form:input type="text" name="txt_email"
                    id="txt_email" path="email" /></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td colspan="2">Age</td>
                <td colspan="3"><form:input type="text" name="txt_age"
                    id="txt_age" path="age" /></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td width="60">&nbsp;</td>
                <td width="68"><input type="submit" name="btn_submit"
                  id="btn_submit" value="Submit" /></td>
                <td width="164"><a href="login">Click here to login >>></a></td>
                <td>&nbsp;</td>
              </tr>

            </table>

          </fieldset></td>
      </tr>
    </table>

  </form:form>
</body>
</html>

Success page code

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
  You are sucessfully login!....
  <br> Welcome <span style="color: red"><b>${emp}</b></span> to Candid Java SpringMVC
  <br>
  <a href="login">Logout</a>
</body>
</html>

Step 8: web xml mapping

<?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">
  <display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

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

Spring hibernate resource file

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

Output Screenshot:

 

Download

Spring Hibernate Integration XML war

Spring Hibernate Integration maven zip