1) Create a dynamic web project called “schoolDBTest”
2) Use maven to get the required jar files
<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.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.6.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy1</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>.\WebContent\WEB-INF\lib</outputDirectory>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3) Create the student database model
package com.schoolDB.database.model;
import javax.persistence.*;
@Entity
@Table(name="Student")
public class Student {
int studentID;
String firstName;
String lastName;
public Student()
{
}
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Id
@GeneratedValue()
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
4) Create student dao
package com.schoolDB.database.dao;
import java.util.List;
import com.schoolDB.database.model.Student;
public interface StudentDao {
public void deleteStudent(int id);
public void addStudent(Student student);
public Student getStudent(int id);
public void editStudent(Student student);
public List<Student> listStudents();
}
package com.schoolDB.database.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.schoolDB.database.model.Student;
@Repository
public class StudentDaoImpl implements StudentDao{
@Autowired
private SessionFactory sessionFactory;
public void addStudent(Student student)
{
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.save(student);
tx.commit();
s.close();
}
public void deleteStudent(int id)
{
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery("delete from Student where id=?").setInteger(0, id);
q.executeUpdate();
tx.commit();
}
public List<Student> listStudents() {
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
@SuppressWarnings("unchecked")
List<Student> list = s.createQuery("from Student").list();
tx.commit();
s.close();
return list;
}
public Student getStudent(int id) {
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from Student where studentid = ?");
q.setMaxResults(1);
q.setInteger(0, id);
Student student = (Student)q.uniqueResult();
tx.commit();
s.close();
return student;
}
public void editStudent(Student student) {
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.update(student);
tx.commit();
s.close();
}
}
5) Create MVC student model
package com.schoolDB.web.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class StudentModel {
public StudentModel() {
}
@NotNull
@Size(min=1, message="First name cannot be empty.")
private String firstName;
@NotNull
@Size(min=1, message="Last name cannot be empty.")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
6) Create student service
package com.schoolDB.database.service;
import java.util.List;
import com.schoolDB.database.model.Student;
import com.schoolDB.web.model.StudentModel;
public interface StudentService {
public void deleteStudent(int id);
public void addStudent(StudentModel student);
public Student getStudent(int id);
public void editStudent(int studentid, StudentModel student);
public List<Student> listStudents();
}
package com.schoolDB.database.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.schoolDB.database.dao.StudentDao;
import com.schoolDB.database.model.Student;
import com.schoolDB.web.model.StudentModel;
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
StudentDao studentdao;
public List<Student> listStudents()
{
return studentdao.listStudents();
}
public void addStudent(StudentModel student) {
studentdao.addStudent(new Student(student.getFirstName(), student.getLastName()));
}
public void deleteStudent(int id)
{
studentdao.deleteStudent(id);
}
public Student getStudent(int id) {
return studentdao.getStudent(id);
}
public void editStudent(int studentid, StudentModel student) {
Student s = new Student(student.getFirstName(), student.getLastName());
s.setStudentID(studentid);
studentdao.editStudent(s);
}
}
7) Create MVC student controller
package com.schoolDB.web.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.validation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.schoolDB.database.model.Student;
import com.schoolDB.database.service.StudentService;
import com.schoolDB.web.model.StudentModel;
@Controller
@RequestMapping(value="/student")
public class StudentController {
Validator validator;
@Autowired
StudentService studentservice;
public StudentController()
{
}
@Autowired
public StudentController(Validator validator)
{
this.validator = validator;
}
@RequestMapping(method=RequestMethod.GET)
public String studentIndex(Map<String, Object> map)
{
map.put("studentList", studentservice.listStudents());
return "student/index";
}
@RequestMapping(value="add", method=RequestMethod.GET)
public String studentAdd(Model model)
{
model.addAttribute("studentModel", new StudentModel());
return "student/studentForm";
}
@RequestMapping(value="add", method=RequestMethod.POST)
public @ResponseBody Map<String, String> create(@RequestBody StudentModel student)
{
Map<String, String> s = new HashMap<String, String>();
Set<ConstraintViolation<StudentModel>> failures = validator.validate(student);
if (!failures.isEmpty()) {
for (ConstraintViolation<StudentModel> constraintViolation : failures) {
s.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
}
}
else
studentservice.addStudent(student);
return s;
}
@RequestMapping(value="delete/{studentid}", method=RequestMethod.GET)
public String delete(@PathVariable String studentid)
{
studentservice.deleteStudent(Integer.parseInt(studentid));
return "redirect:../";
}
@RequestMapping(value="edit", method=RequestMethod.GET)
public String wrongEdit()
{
return "redirect:../";
}
@RequestMapping(value="edit/{studentid}", method=RequestMethod.GET)
public String studentEdit(@PathVariable String studentid, Model model)
{
Student student = (Student)studentservice.getStudent(Integer.parseInt(studentid));
StudentModel m = new StudentModel();
m.setFirstName(student.getFirstName());
m.setLastName(student.getLastName());
model.addAttribute("studentModel", m);
return "student/studentForm";
}
@RequestMapping(value="edit/{studentid}", method=RequestMethod.POST)
public @ResponseBody Map<String, String> studentUpdate(@PathVariable String studentid, @RequestBody StudentModel student)
{
Map<String, String> s = new HashMap<String, String>();
Set<ConstraintViolation<StudentModel>> failures = validator.validate(student);
if (!failures.isEmpty()) {
for (ConstraintViolation<StudentModel> constraintViolation : failures) {
s.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
}
}
else
studentservice.editStudent(Integer.parseInt(studentid), student);
return s;
}
}
8) Create MVC student view
Create the following folder structure /WEB-INF/views/student
Put the following files in the student folder
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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>Students</title>
</head>
<body>
<a href="add/">Add Student</a>
<br><br>
List of Students
<table border="1">
<tr>
<th>first name</th>
<th>last name</th>
</tr>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.firstName }</td>
<td>${student.lastName }</td>
<td><a href="delete/${student.studentID}">Delete</a></td>
<td><a href="edit/${student.studentID}">Edit</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
studentForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>Student Add</title>
<script type="text/javascript" src="<c:url value="/resources/jquery.js" />"></script>
<script type="text/javascript">
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(document).ready(function() {
$("#studentModel").submit(function() {
$("#firstname_error").hide();
$("#lastname_error").hide();
var student = JSON.stringify($('form').serializeObject());
$.ajax({
'type':'POST',
'url':'',
'contentType': 'application/json',
'data': student,
'dataType': 'json',
'success': function(data) {
if(data.firstName != null)
{
$("#firstname_error").show();
$("#firstname_error").html(data.firstName);
}
if(data.lastName != null)
{
$("#lastname_error").show();
$("#lastname_error").html(data.lastName);
}
if(data.firstName == null && data.lastName == null)
window.location = "../";
}
});
return false;
});
});
</script>
</head>
<body>
<form:form modelAttribute="studentModel" action="add" method="post">
<form:label id="firstNameLabel" for="firstName" path="firstName">First Name: </form:label>
<form:input path="firstName" value="${student.firstName}" /><form:errors path="firstName" />
<div id="firstname_error" style="display:none"></div>
<br>
<form:label id="lastNameLabel" for="lastName" path="lastName">Last Name: </form:label>
<form:input path="lastName" value="${student.lastName}" /><form:errors path="lastName" />
<div id="lastname_error" style="display:none"></div>
<br>
<input id="submit" type="submit" value="submit" />
</form:form>
</body>
</html>
9) Create configuration files in WEB-INF folder
servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for @Components to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="com.schoolDB" />
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="welcome" />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:file:/schoolDBTest/schoolDBTest;DB_CLOSE_DELAY=-1;MVCC=TRUE"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="annotatedClasses">
<list>
<value>com.schoolDB.database.model.Student</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.format_sql=true
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
</beans>
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>schoolDBTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
10) Create folder called resources under WEB-INF. Put jquery.js in resources folder
Open browser to http://localhost:8080/schoolDBTest/student/