Follow Nirav Raval

Thursday 1 August 2013


Spring MVC - Hibernate Demo Application


Hello Friends,

Nice to see you again.
In Previous Sessions  we have seen  Spring MVC with Annotation Demo. And learn how they work.
Today, we will see the example of  Spring MVC with Hibernate basic tutorial.

This demo I have created using Netbeans IDE 7.1.2.
Netbeans provide Spring Project with Hibernate, So no need to find out every Jars as it provides by Netbeans itself.

Ok Here we will create one Student Register Application demo which we previosuly develope without database.

Now we will extend that with adding Hibernate support to persist our data in MySQL Server.

Below is our final output.

Student Registration Demo


For create this application, I have create one Database Table "Student" in MySQL Server as below.
---------------------------------------------------------------------------------------------------------------------------
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(30) DEFAULT NULL,
  `lastname` varchar(30) DEFAULT NULL,
  `telephone` varchar(15) DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
---------------------------------------------------------------------------------------------------------------------------

Project Structure


Source Code:
---------------------------------------------------------------------------------------------------------------------------
(1) 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">
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

---------------------------------------------------------------------------------------------------------------------------
(2) spring-servlet.xml
---------------------------------------------------------------------------------------------------------------------------
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
<context:component-scan base-package="com.j2eedeveloper" />

<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/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="root" />

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

---------------------------------------------------------------------------------------------------------------------------
(3) jdbc.properties
---------------------------------------------------------------------------------------------------------------------------

jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

---------------------------------------------------------------------------------------------------------------------------
(4) 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>
        <mapping class="com.j2eedevloper.model.Student" />
    </session-factory>
   
</hibernate-configuration>

---------------------------------------------------------------------------------------------------------------------------
(5) messages_en.properties
---------------------------------------------------------------------------------------------------------------------------
label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addStudent=Add Student
label.title=Student Manager

label.footer=&copy; niravj2eedeveloper.blogspot.com

---------------------------------------------------------------------------------------------------------------------------
(6) StudentController.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.controller;

import com.j2eedeveloper.service.StudentService;
import com.j2eedevloper.model.Student;
import java.util.Map;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {

        map.put("student", new Student());
        map.put("studentList", studentService.listStudent());

        return "student";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("student") Student student) {

        studentService.addStudent(student);

        return "redirect:/index";
    }

    @RequestMapping("/delete/{studentId}")
    public String deleteContact(@PathVariable("studentId") Integer studentId) {

        studentService.removeStudent(studentId);

        return "redirect:/index";
    }

}

---------------------------------------------------------------------------------------------------------------------------
(7) StudentDAO.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.dao;

import com.j2eedevloper.model.Student;
import java.util.List;

public interface StudentDAO {

    public void addStudent(Student student);

    public List<Student> listStudent();

    public void removeStudent(Integer id);

}

---------------------------------------------------------------------------------------------------------------------------
(8) StudenttDAOImpl.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.dao;

import com.j2eedevloper.model.Student;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class StudenttDAOImpl implements StudentDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addStudent(Student student) {
        sessionFactory.getCurrentSession().save(student);
    }

    public List<Student> listStudent() {

        return sessionFactory.getCurrentSession().createQuery("from Student").list();
    }

    public void removeStudent(Integer id) {
        Student student = (Student) sessionFactory.getCurrentSession().load(
                Student.class, id);
        if (null != student) {
            sessionFactory.getCurrentSession().delete(student);
        }

    }

}

---------------------------------------------------------------------------------------------------------------------------
(9) StudentService.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.service;

import com.j2eedevloper.model.Student;
import java.util.List;

public interface StudentService {

    public void addStudent(Student student);

    public List<Student> listStudent();

    public void removeStudent(Integer id);

}

---------------------------------------------------------------------------------------------------------------------------
(10) StudentServiceImpl.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.service;

import com.j2eedeveloper.dao.StudentDAO;
import com.j2eedevloper.model.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    @Transactional
    public void addStudent(Student student) {
        studentDAO.addStudent(student);
    }

    @Transactional
    public List<Student> listStudent() {

        return studentDAO.listStudent();
    }

    @Transactional
    public void removeStudent(Integer id) {
        studentDAO.removeStudent(id);
    }

}

---------------------------------------------------------------------------------------------------------------------------
(11) Student.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedevloper.model;

import javax.persistence.*;

@Entity
@Table(name = "Student")
public class Student {

    @Id
    @Column(name = "ID")
    @GeneratedValue
    private Integer id;
    @Column(name = "FIRSTNAME")
    private String firstname;
    @Column(name = "LASTNAME")
    private String lastname;
    @Column(name = "EMAIL")
    private String email;
    @Column(name = "TELEPHONE")
    private String telephone;

    public String getEmail() {
        return email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

---------------------------------------------------------------------------------------------------------------------------
(12) student.jsp
---------------------------------------------------------------------------------------------------------------------------

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
    <head>
        <title>Spring 3 MVC Hibernate - Student Manager</title>
        <style type="text/css">
            body {
                font-family: sans-serif;
            }
            .data, .data td {
                border-collapse: collapse;
                width: 100%;
                border: 1px solid #aaa;
                margin: 2px;
                padding: 2px;
            }
            .data th {
                font-weight: bold;
                background-color: #5C82FF;
                color: white;
            }
        </style>
    </head>
    <body>

        <h2><spring:message code="label.title"/></h2>

        <form:form method="post" action="add.html" commandName="student">

            <table>
                <tr>
                    <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
                    <td><form:input path="firstname" /></td>
                </tr>
                <tr>
                    <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
                    <td><form:input path="lastname" /></td>
                </tr>
                <tr>
                    <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
                    <td><form:input path="email" /></td>
                </tr>
                <tr>
                    <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
                    <td><form:input path="telephone" /></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="<spring:message code="label.addStudent"/>"/>
                    </td>
                </tr>
            </table>
        </form:form>


        <h3>Students</h3>
        <c:if  test="${!empty studentList}">
            <table class="data">
                <tr>
                    <th style="width: 40%">Name</th>
                    <th style="width: 30%">Email</th>
                    <th style="width: 20%">Telephone</th>
                    <th>&nbsp;</th>
                </tr>
                <c:forEach items="${studentList}" var="student">
                    <tr>
                        <td style="width: 40%">${student.lastname} ${student.firstname} </td>
                        <td style="width: 30%">${student.email}</td>
                        <td style="width: 20%">${student.telephone}</td>
                        <td><a href="delete/${student.id}">delete</a></td>
                    </tr>
                </c:forEach>
            </table>
        </c:if>

        <br/>
        <hr/>
        <h3><spring:message code="label.footer"/></h3>
        <hr/>
    </body>

</html>

---------------------------------------------------------------------------------------------------------------------------
Now run URL http://localhost:8080/SpringHibernate/index  in your browser.
---------------------------------------------------------------------------------------------------------------------------
Hope you find this helpful....!

Friday 19 July 2013

Spring MVC with Annotation

Hello Friends,

Nice to see you again.
In Previous Sessions  we have seen  Hibernate Basic Demo. And learn how they work.
Today, we will see the example of  Spring MVC with annotation basic tutorial.

This demo I have created using Netbeans IDE 7.1.2.
Netbeans provide Spring Project, So no need to find out every Jars as it provides by Netbeans itself.

Ok Here we will create one Student Register Application demo.
Where first page will have URL redirect for New Student Registration Page.
When Registration done then view registration page will call.

Ok below is the screen dump showing my project structure.

And below is the Libraries added by Netbeans for Spring Project. You choose which you want to use.



Output: 

Run http://localhost:8080/StudentSpringDemo/addStudent


1st Scrren:


2nd Screen:


3rd Screen:

Source Code:
---------------------------------------------------------------------------
(1) Web.xml
---------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Spring MVC Form Handling With Nirav Raval</display-name>

    <servlet>
        <servlet-name>J2eeDeveloper</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>J2eeDeveloper</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
</web-app>

---------------------------------------------------------------------------
(2) J2eeDeveloper-servlet.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: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="com.j2eedeveloper" />   
       
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

---------------------------------------------------------------------------
(3) StudentController.java
---------------------------------------------------------------------------
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.j2eedeveloper;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
/**
 *
 * @author Nirav
 */
@Controller
public class StudentController {
 
 
    @RequestMapping(value="/index", method= RequestMethod.GET)
    public ModelAndView Startup(){
        return new ModelAndView("index");
     
    }
 
    @RequestMapping(value="/student", method= RequestMethod.GET)
    public ModelAndView Student(){
        return new ModelAndView("Student", "command", new Student());
    }
 
    @RequestMapping(value="/addStudent", method = RequestMethod.POST)
    public String addStudent(@ModelAttribute("SpringWeb")Student student, ModelMap model){
        model.addAttribute("id", student.getId());
        model.addAttribute("rollno", student.getRollno());
        model.addAttribute("age", student.getAge());
        model.addAttribute("name", student.getName());
     
        return "result";
    }
}

---------------------------------------------------------------------------
(4) index.jsp
---------------------------------------------------------------------------

<%--
    Document   : index
    Created on : July 19, 2013, 9:38:17 PM
    Author     : Nirav
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Spring MVC DemoWith Nirav</title>
    </head>
    <body>
        <h1>Spring MVC DemoWith Nirav</h1>
        <a href="/StudentSpringDemo/student/">Add Student</a>
    </body>
</html>


---------------------------------------------------------------------------
(5) Student.jsp
---------------------------------------------------------------------------

<%--
    Document   : Student
    Created on : Jun 10, 2013, 9:49:55 PM
    Author     : Nirav
--%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling With Nirav Raval</title>
</head>
<body>

<h2>Student Information</h2>
<form:form method="POST" action="/StudentSpringDemo/addStudent">
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td><form:label path="age">Age</form:label></td>
        <td><form:input path="age" /></td>
    </tr>
    <tr>
        <td><form:label path="rollno">Roll No</form:label></td>
        <td><form:input path="rollno" /></td>
    </tr>
    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table> 
</form:form>
</body>
</html>



---------------------------------------------------------------------------
(6) result.jsp
---------------------------------------------------------------------------
<%--
    Document   : result
    Created on : Jun 19, 2013, 9:51:52 PM
    Author     : Nirav
--%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling With Nirav Raval</title>
</head>
<body>

<h2>Submitted Student Information</h2>
   <table>
    <tr>
        <td>Name</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>Age</td>
        <td>${age}</td>
    </tr>
    <tr>
        <td>Roll No</td>
        <td>${rollno}</td>
    </tr>
    <tr>
        <td>ID</td>
        <td>${id}</td>
    </tr>
</table> 
</body>
</html>

---------------------------------------------------------------------------
 
Now run URL http://localhost:8080/StudentSpringDemo/addStudent  in your browser.
 
Hope you find this helpful....!