Dependency Injection Pattern in Java using Spring

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/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.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</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>.\lib</outputDirectory>
                            <!-- other configurations here -->
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

IExams.java

package exam;

public interface IExams {
	String generateExam();
}

EnglishExam.java

package exam;

public class EnglishExam implements IExams {

	String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String generateExam() {
		return name + ", English Exam Generated";
	}

}

MathExams.java

package exam;

public class MathExams implements IExams {
	String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String generateExam() {
		return name + ", Math Exam Generated";
	}

}

ExamService.java

package exam;

public class ExamService {
	IExams exam;

	public IExams getExam() {
		return exam;
	}

	public void setExam(IExams exam) {
		this.exam = exam;
	}
	
	public String generateExam()
	{
		return exam.generateExam();
	}
}

Exams.java

package exam;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Exams {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
		ExamService exams = (ExamService) context.getBean("ExamService");
		String exam = exams.generateExam();
		System.out.println(exam);
		context.close();
	}
}

bean.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
    <bean id="EnglishExam" class="exam.EnglishExam">
        <property name="Name" value="john"></property>
    </bean>
    
    <bean id="MathExams" class="exam.MathExams">
        <property name="Name" value="steve"></property>
    </bean>
    <bean id="ExamService" class="exam.ExamService">
        <property name="Exam">
            <!-- <ref local="MathExams"/> -->
            <ref local="EnglishExam"/>
        </property>
    </bean>       
</beans>

Custom SQL queries using Hibernate

Database Schema
student
id int, auto_increment, primary key
fname char(20)
lname char(20)
age int

grade
id int, auto_increment, primary key
studentid int,
grade int

1) Use Maven to get the hibernate and H2 jars

<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.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>
	</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>.\lib</outputDirectory>
							<!-- other configurations here -->
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

2) Place the hibernate config file in the “src” folder.
hibernate.cfg.xml

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

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:file:schoolDB;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.tutorial.Student"/>
        <mapping class="com.tutorial.Course"/>
        <mapping class="com.tutorial.Grade"/>

    </session-factory>

</hibernate-configuration>

3) CustomSQL.java

package com.customsql;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.transform.Transformers;

public class CustomSQL {
	public static class gradeClass
	{
		int grade;
		int id;
		
		public int getGRADE() {
			return grade;
		}
		public void setGRADE(int grade) {
			this.grade = grade;
		}
		public int getID() {
			return id;
		}
		public void setID(int id) {
			this.id = id;
		}
	}
	public static void main(String[] arg) {
		Configuration configure = new Configuration().configure();
		ServiceRegistryBuilder serviceRegistry = new ServiceRegistryBuilder().applySettings(configure.getProperties());
		SessionFactory sessionFactory = configure.buildSessionFactory(serviceRegistry.buildServiceRegistry());
		
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<gradeClass> list = session.createSQLQuery("select student.id, grade from student inner join grade on student.id = grade.studentid")
			.setResultTransformer(Transformers.aliasToBean(gradeClass.class)).list();
		for (gradeClass g : list) {
			System.out.println(g.getGRADE());
		}
	}
}

Spring and Hibernate

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/

Hibernate

1) Create a project called “SchoolDB” in eclipse
2) Use Maven to get the hibernate and H2 jars

<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.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>
	</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>.\lib</outputDirectory>
							<!-- other configurations here -->
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

3) Place the hibernate config file in the “src” folder.
hibernate.cfg.xml

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

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:file:schoolDB;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.tutorial.Student"/>
        <mapping class="com.tutorial.Course"/>
        <mapping class="com.tutorial.Grade"/>

    </session-factory>

</hibernate-configuration>

4) Write the code
Student.java

package com.tutorial;

import javax.persistence.*;

@Entity
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;
	}
}

Course.java

package com.tutorial;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Course {
	public Course()
	{
		
	}
	public Course(String courseID, String courseName) {
		this.courseID = courseID;
		this.courseName = courseName;
	}
	String courseID;
	String courseName;
	
	@Id
	public String getCourseID() {
		return courseID;
	}
	public void setCourseID(String courseID) {
		this.courseID = courseID;
	}
	public String getCourseName() {
		return courseName;
	}
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}
}

Grade.java

package com.tutorial;

import javax.persistence.*;

@Entity
public class Grade {
	public Grade()
	{
		
	}
	public Grade(Student student, Course course, int grade) {
		this.student = student;
		this.course = course;
		this.grade = grade;
	}
	int gradeID;
	Student student;
	Course course;
	int grade;
	
	@Id
	@GeneratedValue()
	public int getGradeID() {
		return gradeID;
	}
	public void setGradeID(int gradeID) {
		this.gradeID = gradeID;
	}
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name="studentID")
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name="courseID")
	public Course getCourse() {
		return course;
	}
	public void setCourse(Course course) {
		this.course = course;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	
}

SchoolDB.java

package com.tutorial;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class SchoolDB {
	private SessionFactory sessionFactory;
	
	void CreateStudents()
	{
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save( new Student( "John", "Smith" ) );
		session.save( new Student( "George", "Washington" ) );
		session.getTransaction().commit();
		session.close();
	}
	
	void CreateCourses()
	{
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save( new Course( "M1001", "Math" ) );
		session.save( new Course( "P1001", "Physics" ) );
		session.save( new Course( "S1001", "Science" ) );
		session.getTransaction().commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	void SubmitGrades()
	{
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		List <Course> course = session.createQuery("from Course where courseName='Physics'").list();
		List <Student> student = session.createQuery("from Student where firstName='John'").list();
		session.save(new Grade(student.get(0), course.get(0), 90));
		
		course = session.createQuery("from Course where courseName='Math'").list();
		session.save(new Grade(student.get(0), course.get(0), 80));
		
		course = session.createQuery("from Course where courseName='Science'").list();
		student = session.createQuery("from Student where firstName='George'").list();
		session.save(new Grade(student.get(0), course.get(0), 50));
		
		session.getTransaction().commit();
		session.close();
	}
	
	public void run()
	{
		Configuration configure = new Configuration().configure();
		ServiceRegistryBuilder serviceRegistry = new ServiceRegistryBuilder().applySettings(configure.getProperties());
		sessionFactory = configure.buildSessionFactory(serviceRegistry.buildServiceRegistry());
		
		CreateStudents();
		CreateCourses();
		SubmitGrades();
		
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List <Grade>grades = session.createQuery("from Grade").list();
		System.out.println();
		for (Grade grade : grades) {
			System.out.println(grade.getStudent().getFirstName() + " "+ 
					grade.getStudent().getLastName() + " "+ 
					grade.getCourse().getCourseName() + " " +
					grade.getGrade());
		}
		session.close();
		
		if ( sessionFactory != null ) {
			sessionFactory.close();
		}
	}
	public static void main(String[] args) {
		new SchoolDB().run();
	}
}

Simple Forms using MVC in Spring (Java) with Ajax

1) Create a new “Dynamic Web Project” in Eclipse. Name it “SimpleProject”.
Next, obtain the following jar files

hibernate-validator-4.3.0.Final.jar
jboss-logging-3.1.2.GA.jar
jstl-1.2.jar
spring-beans-3.2.0.M2.jar
spring-context-3.2.0.M2.jar
spring-core-3.2.0.M2.jar
spring-expression-3.2.0.M2.jar
spring-web-3.2.0.M2.jar
spring-webmvc-3.2.0.M2.jar
standard-1.1.2.jar
validation-api-1.0.0.GA.jar
jackson-core-asl-1.7.1.jar

Optional: Use maven to get the jar files. Put the following pom.xml in the same directory as your project

<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>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>
	</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>

2) Create a database class

package com.simplesearch.database;

import java.util.HashMap;
import java.util.Map;

public class SearchDB {
	Map <Integer, String>category;
	
	public Map<Integer, String> getCategory() {
		return category;
	}

	public void setCategory(Map<Integer, String> category) {
		this.category = category;
	}

	public SearchDB()
	{
		category = new HashMap<Integer, String>();
		category.put(10, "Computers");
		category.put(11, "TV");
		category.put(12, "Tablet");
	}
}

3) Create the model class

package com.simplesearch.model;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;

public class SearchModel {
	@NotNull(message="Search cannot be null.")
	@Size(min=1, message="Search cannot be empty.")
	@Pattern(regexp="^[a-z]*$", message="Must contain letters only.")
	String searchTerm;
	
	@Range(min=10, max=12, message="Please select a category.")
	@NotNull(message="Invalid category.")
	int category;
	public String getSearchTerm() {
		return searchTerm;
	}
	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}
	public int getCategory() {
		return category;
	}
	public void setCategory(int category) {
		this.category = category;
	}
}

4) Create the controller class

package com.simplesearch.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.simplesearch.database.SearchDB;
import com.simplesearch.model.SearchModel;

@Controller
@RequestMapping(value="/search")
public class SimpleSearchController {
	Validator validator;
	SearchDB db;
	
	public SimpleSearchController()
	{
		db = new SearchDB();
	}
	
	@Autowired
	public SimpleSearchController(Validator validator)
	{
		this.validator = validator;
		db = new SearchDB();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "search/index";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public @ResponseBody Map<String, String> create(@RequestBody SearchModel search)
	{
		Map<String, String> s = new HashMap<String, String>();
		Set<ConstraintViolation<SearchModel>> failures = validator.validate(search);

		if (!failures.isEmpty()) {
			for (ConstraintViolation<SearchModel> constraintViolation : failures) {
				s.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
			}
		}

		return s;
	}
	
	@RequestMapping(value="searchResults", method=RequestMethod.GET)
	public String getResult(Model m, HttpServletRequest request)
	{
		SearchModel s = new SearchModel();
		Map<java.lang.String,java.lang.String[]> rMap = request.getParameterMap();
		String []category = rMap.get("category");
		String []searchTerm = rMap.get("searchTerm");
		if(category != null)
		{
			try
			{
				int cat = Integer.parseInt(category[0]);
				s.setCategory(cat);
			}catch(Exception e)
			{
				
			}
		}
		if(searchTerm != null)
		{
			s.setSearchTerm(searchTerm[0]);
		}
		
		Set<ConstraintViolation<SearchModel>> failures = validator.validate(s);
		if (!failures.isEmpty()) {
			m.addAttribute("errorMessages", "Invalid input");
		}
		else
		{
			m.addAttribute("categories", db.getCategory());
			m.addAttribute("searchModel", s);
		}
		
		return "search/searchResults";
	}
	
	@ModelAttribute("category")
	protected Map<Integer, String> categoryList(HttpServletRequest request) throws Exception {
		return db.getCategory();
	}
}

5) Create the views
Create folder “views” under WEB-INF then create folder “search” under “views”
Create index.jsp

<%@ 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">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search</title>

<script type="text/javascript" src="<c:url value="resources/jquery-1.8.2.min.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() {
	$("#SearchModel").submit(function() {
		$("#category_error").hide();
		$("#searchTerm_error").hide();
		var search = JSON.stringify($('form').serializeObject());
		$.ajax({
			'type':'POST',
			'url':'',
			'contentType': 'application/json',
			'data': search,
			'dataType': 'json',
			'success': function(data) {
				if(data.category != null)
				{
					$("#category_error").show();
					$("#category_error").html(data.category);
				}
				if(data.searchTerm != null)
				{
					$("#searchTerm_error").show();
					$("#searchTerm_error").html(data.searchTerm);
				}
				
				if(data.category == null && data.searchTerm == null)
				{
					window.location.replace("search/searchResults?" + $('form').serialize());
				}
			}
		});
		return false;
	});
});
</script>
</head>
<body>
	<form:form modelAttribute="SearchModel" action="search" method="post">
		Category: 
		<form:select path="category">
			<form:option value="0">--Select--</form:option>
			<form:options items="${category}" />
		</form:select>
		<div id="category_error" style="display:none"></div>
		<br>
		<form:label	id="searchTermLabel" for="searchTerm" path="searchTerm" cssErrorClass="error">Search: </form:label>
		<form:input path="searchTerm" /><form:errors path="searchTerm" />
		<div id="searchTerm_error" style="display:none"></div>
		<br>
		<p>
			<input id="create" type="submit" value="Create" />
		</p>
	</form:form>

</body>
</html>

Create searchResults.jsp

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ 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 uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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>Search</title>
</head>
<body>
	${errorMessages}

	<c:if test="${searchModel != null}">
		You searched for ${searchModel.searchTerm} in category: ${categories[searchModel.category]}
	</c:if>
</body>
</html>

Create welcome.jsp in the “views” folder

<%@ 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>Insert title here</title>
</head>
<body>
<c:redirect url="search" />
</body>
</html>

6) Create “resources” folder in WebContent folder (same level as WEB-INF). Put jquery js file in resources folder
7) Create the context configuration 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.simplesearch" />
 
    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />
    <mvc:view-controller path="/" view-name="welcome"  />
 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
    <mvc:resources mapping="/resources/**" location="/resources/" />
</beans>

Note: Make sure to replace “com.simplesearch” with your package.
Optional: If this configuration is not present, you will need to provide the full path in the get request.

 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>

For example:
Without the configuration

	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "/WEB-INF/views/search/index.jsp";
	}

With the configuration

	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "search/index";
	}

8) Create/Modify the web.xml (in WEB-INF)

<?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>SimpleSearch</display-name>
    <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>

Note: Make sure “/WEB-INF/servlet-context.xml” points to your spring configuration

Finally,
go to http://localhost:8080/SimpleProject in your browser.

Simple Forms using MVC in Spring (Java)

1) Create a new “Dynamic Web Project” in Eclipse. Name it “SimpleProject”.
Next, obtain the following jar files

hibernate-validator-4.3.0.Final.jar
jboss-logging-3.1.2.GA.jar
jstl-1.2.jar
spring-beans-3.2.0.M2.jar
spring-context-3.2.0.M2.jar
spring-core-3.2.0.M2.jar
spring-expression-3.2.0.M2.jar
spring-web-3.2.0.M2.jar
spring-webmvc-3.2.0.M2.jar
standard-1.1.2.jar
validation-api-1.0.0.GA.jar

Optional: Use maven to get the jar files. Put the following pom.xml in the same directory as your project

<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.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>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>
	</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>

2) Create a database class

package com.simplesearch.database;

import java.util.HashMap;
import java.util.Map;

public class SearchDB {
	Map <Integer, String>category;
	
	public Map<Integer, String> getCategory() {
		return category;
	}

	public void setCategory(Map<Integer, String> category) {
		this.category = category;
	}

	public SearchDB()
	{
		category = new HashMap<Integer, String>();
		category.put(10, "Computers");
		category.put(11, "TV");
		category.put(12, "Tablet");
	}
}

3) Create the model class

package com.simplesearch.model;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;

public class SearchModel {
	@Size(min = 1, message="Search cannot be empty.")
	@Pattern(regexp="^[a-z]+$", message="Must contain letters only.")
	String searchTerm;
	
	@Range(min=10, max=12, message="Please select a category.")
	int category;
	public String getSearchTerm() {
		return searchTerm;
	}
	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}
	public int getCategory() {
		return category;
	}
	public void setCategory(int category) {
		this.category = category;
	}
}

4) Create the controller class

package com.simplesearch.controller;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

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

import com.simplesearch.database.SearchDB;
import com.simplesearch.model.SearchModel;

@Controller
@RequestMapping(value="/search")
public class SimpleSearchController {
	Validator validator;
	SearchDB db;
	
	public SimpleSearchController()
	{
		db = new SearchDB();
	}
	@Autowired
	public SimpleSearchController(Validator validator)
	{
		this.validator = validator;
		db = new SearchDB();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "search/index";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public void create(SearchModel search, HttpServletResponse response)
	{
		Set<ConstraintViolation<SearchModel>> failures = validator.validate(search);

		try {
			if (!failures.isEmpty()) {
				response.getWriter().print("Search failed. Reason(s): ");
				response.getWriter().println();
				for (ConstraintViolation<SearchModel> constraintViolation : failures) {
					response.getWriter().println(constraintViolation.getMessage());
				}
			}
			else
			{
				response.getWriter().println("You searched for: " + search.getSearchTerm() + 
						" in category " + db.getCategory().get(search.getCategory()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@ModelAttribute("category")
	protected Map<Integer, String> categoryList(HttpServletRequest request) throws Exception {
		return db.getCategory();
	}
}

5) Create the views
Create folder “views” under WEB-INF then create folder “search” under “views”
Create index.jsp

<%@ 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">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search</title>
</head>
<body>
	<form:form modelAttribute="SearchModel" action="search" method="post">
		Category: 
		<form:select path="category">
			<form:option value="0">--Select--</form:option>
			<form:options items="${category}" />
		</form:select>
		<br>
		<br>
		<form:label	id="searchTermLabel" for="searchTerm" path="searchTerm" cssErrorClass="error">Search: </form:label>
		<form:input path="searchTerm" /><form:errors path="searchTerm" />
		<br>
		<p>
			<input id="create" type="submit" value="Create" />
		</p>
	</form:form>

</body>
</html>

6) Create the context configuration 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.simplesearch" />
 
    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />
 
 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

Note: Make sure to replace “com.simplesearch” with your package.
Optional: If this configuration is not present, you will need to provide the full path in the get request.

 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>

For example:
Without the configuration

	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "/WEB-INF/views/search/index.jsp";
	}

With the configuration

	@RequestMapping(method=RequestMethod.GET)
	public String getCreateSearch(Model model)
	{
		model.addAttribute("SearchModel", new SearchModel());
		return "search/index";
	}

7) Create/Modify the 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>SimpleSearch</display-name>
    <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>

Note: Make sure “/WEB-INF/servlet-context.xml” points to your spring configuration
8) Run on Tomcat. The address should be “http://localhost:8080/SimpleProject/search&#8221;

Generating Prime Numbers with Java RMI using HTTP Server

Create simple HTTP Server

package http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerLite {
  public static void main(String[] args) throws IOException {
    InetSocketAddress addr = new InetSocketAddress(9876);
    HttpServer server = HttpServer.create(addr, 0);

    server.createContext("/", new MyHandler());
    server.start();
    System.out.println("Server is listening on port 9876" );
  }
}

class MyHandler implements HttpHandler {
	public void handle(HttpExchange exchange) throws IOException {
		String requestMethod = exchange.getRequestMethod();
		if (requestMethod.equalsIgnoreCase("GET")) {
			try
			{
				URI uri = exchange.getRequestURI();
				Path path = FileSystems.getDefault().getPath("../jar/",uri.getPath().substring(1));
				byte[] b = Files.readAllBytes(path);
				Headers responseHeaders = exchange.getResponseHeaders();
				responseHeaders.set("Content-Type", "application/java-archive");
				responseHeaders.set("Content-Length",
						((Integer) b.length).toString());
				exchange.sendResponseHeaders(200, 0);
	
				OutputStream responseBody = exchange.getResponseBody();
				responseBody.write(b);
				responseBody.close();
			}catch(Exception e)
			{
				Headers responseHeaders = exchange.getResponseHeaders();
				responseHeaders.set("Content-Type", "text/html");
				exchange.sendResponseHeaders(404, 0);
				OutputStream responseBody = exchange.getResponseBody();
				responseBody.write("error: file not found".getBytes());
				responseBody.close();
			}
		}
	}
}

The HTTP server will look for files in a directory called jar which is located one level above current directory.
NOTE: For the http server to compile in Eclipse, make sure the JRE System Library is set to “Workspace default JRE (jre7)”
Create PrimeNumber RMI server

package server;

import java.util.List;

public interface PrimeTask {
	List<Long> getListofPrimes(Long n);
	Boolean isPrime(Long n);
}
package server;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface PrimeCompute extends Remote {
	List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException;
	Boolean isPrime(PrimeTask t, Long n) throws RemoteException;
}
package server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

public class PrimeComputeEngine implements PrimeCompute{
	public List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException
	{
		return t.getListofPrimes(n);
	}

	public Boolean isPrime(PrimeTask t, Long n) throws RemoteException
	{
		return t.isPrime(n);
	}

	public static void main(String[] args) {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
		try
		{
			String name = "PrimeCompute";
			PrimeCompute engine = new PrimeComputeEngine();
			PrimeCompute stub =
	                (PrimeCompute) UnicastRemoteObject.exportObject(engine, 0);
			Registry registry = LocateRegistry.getRegistry();
	        registry.rebind(name, stub);
	        System.out.println("ComputeEngine bound");
		} catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
	}
}

Create a jar file called PrimeCompute.jar with the following classes: PrimeCompute and PrimeTask. Make sure to save it to the jar folder because the HTTP server will read from the jar folder.

For step by step instructions, go to Generating Prime Numbers with Java RMI

Create PrimeNumber RMI client

package client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import server.PrimeTask;

class PrimeObject implements PrimeTask, Serializable
{
	private static final long serialVersionUID = 8954L;

	public PrimeObject()
	{

	}

	@Override
	public List<Long> getListofPrimes(Long n) {
        List<Long> temp = new ArrayList<Long>();

        for (long i = 1; i <= n; i++)
        {
            if (isPrime(i))
                temp.add(i);
        }
        return temp;
	}

	@Override
	public Boolean isPrime(Long n) {
        if (n == 1)
            return false;
        else if (n < 4)
            return true;
        else if (n % 2 == 0)
            return false;
        else if (n < 9)
            return true;
        else if (n % 3 == 0)
            return false;
        else
        {
            int r = (int)Math.floor(Math.sqrt(n));
            int f = 5;
            while (f <= r)
            {
                if (n % f == 0)
                    return false;
                if (n % (f + 2) == 0)
                    return false;
                f = f + 6;
            }
        }
        return true;
	}
}
package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import server.PrimeCompute;
import server.PrimeTask;

public class PrimeNumberUtils {
	public static void main(String[] args) {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
		
		try {
			String name = "PrimeCompute";
			Registry registry = LocateRegistry.getRegistry(args[0]);
			PrimeCompute prime = (PrimeCompute) registry.lookup(name);
			PrimeTask o = new PrimeObject();
			Long l = 1000000L;
			List<Long> p = prime.getListofPrimes(o, l);
			for (Long n : p) {
				System.out.println(n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Add reference to the PrimeCompute.jar so the client will compile.

Create a jar file called PrimeObject.jar with the following classes: PrimeObject. Make sure to save it to the jar folder because the HTTP server will read from the jar folder.

Create Security Policy
Create a file called server.policy (and put it in your server project directory). Create a file called client.policy (and put it in your client project directory). Both server.policy and client.policy contains the following:

grant{
permission java.security.AllPermission;
};

Configurations for Java Applications
PrimeNumberServer

Make sure the VM arguments has the following:

-Djava.security.policy=server.policy -Djava.rmi.server.codebase="http://localhost:9876/PrimeCompute.jar http://localhost:9876/PrimeObject.jar"

Replace localhost with your http webserver address.

PrimeNumberClient

Make sure the VM arguments has the following:

-Djava.security.policy=client.policy

HTTPServerLite
No configuration needed.

Running the apps
Run the following in order:
1) rmiregistry
2) HTTP Server
3) PrimeNumberServer
4) PrimeNumberClient

Generating Prime Numbers with Java RMI

Code for server

package server;

import java.util.List;

public interface PrimeTask {
	List<Long> getListofPrimes(Long n);
	Boolean isPrime(Long n);
}
package server;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface PrimeCompute extends Remote {
	List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException;
	Boolean isPrime(PrimeTask t, Long n) throws RemoteException;
}
package server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

public class PrimeComputeEngine implements PrimeCompute{
	public List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException
	{
		return t.getListofPrimes(n);
	}

	public Boolean isPrime(PrimeTask t, Long n) throws RemoteException
	{
		return t.isPrime(n);
	}

	public static void main(String[] args) {
		try
		{
			String name = "PrimeCompute";
			PrimeCompute engine = new PrimeComputeEngine();
			PrimeCompute stub =
	                (PrimeCompute) UnicastRemoteObject.exportObject(engine, 0);
			Registry registry = LocateRegistry.getRegistry();
	        registry.rebind(name, stub);
	        System.out.println("ComputeEngine bound");
		} catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
	}
}

Code for client

package client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import server.PrimeTask;

class PrimeObject implements PrimeTask, Serializable
{
	private static final long serialVersionUID = 8954L;

	public PrimeObject()
	{

	}

	@Override
	public List<Long> getListofPrimes(Long n) {
        List<Long> temp = new ArrayList<Long>();

        for (long i = 1; i <= n; i++)
        {
            if (isPrime(i))
                temp.add(i);
        }
        return temp;
	}

	@Override
	public Boolean isPrime(Long n) {
        if (n == 1)
            return false;
        else if (n < 4)
            return true;
        else if (n % 2 == 0)
            return false;
        else if (n < 9)
            return true;
        else if (n % 3 == 0)
            return false;
        else
        {
            int r = (int)Math.floor(Math.sqrt(n));
            int f = 5;
            while (f <= r)
            {
                if (n % f == 0)
                    return false;
                if (n % (f + 2) == 0)
                    return false;
                f = f + 6;
            }
        }
        return true;
	}
}
package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import server.PrimeCompute;
import server.PrimeTask;

public class PrimeNumberUtils {
	public static void main(String[] args) {
		try {
			String name = "PrimeCompute";
			Registry registry = LocateRegistry.getRegistry(args[0]);
			PrimeCompute prime = (PrimeCompute) registry.lookup(name);
			PrimeTask o = new PrimeObject();
			Long l = 1000000L;
			List<Long> p = prime.getListofPrimes(o, l);
			for (Long n : p) {
				System.out.println(n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Eclipse with all the java files

Create jar for RMI codebase


Start rmiregistry

Create Java Application for server

Make sure the VM Arguments has the following

-Djava.rmi.server.codebase=file:/C:\RMI\PrimeNumbersRMI\PrimeCompute.jar

Replace C:\RMI\PrimeNumbersRMI\PrimeCompute.jar with your path

Create Java Application for Client

Make sure the Program Arguments point to server. In this case, it is localhost because the server and client is run from the same machine.
Make sure the VM Arguments has the following

-Djava.rmi.server.codebase=file:/C:\RMI\PrimeNumbersRMI\PrimeCompute.jar

Replace C:\RMI\PrimeNumbersRMI\PrimeCompute.jar with your path

Run Java Application for server first, then run Java Application for client

Serialization in Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationTest {
static class Person implements Serializable
{
private static final long serialVersionUID = 1411808257424672585L;

public Person(String fname, String lname, String title, String ss,
String birthYear) {
this.fname = fname;
this.lname = lname;
this.title = title;
this.ss = ss;
this.birthYear = birthYear;
}
String fname;
String lname;
String title;
transient String ss;
String birthYear;

@Override
public String toString() {
return "Person [fname=" + fname + ", lname=" + lname + ", title="
+ title + ", ss=" + ss + ", birthYear=" + birthYear + "]";
}

}
public static void main(String[] args) throws Exception{
Person p = new Person("John","Doe", "Mr.", "123456789", "1980");
FileOutputStream outStream = new FileOutputStream("Person.bin");
ObjectOutputStream s = new ObjectOutputStream(outStream);
s.writeObject(p);
s.close();

FileInputStream inStream = new FileInputStream("Person.bin");
ObjectInputStream s1 = new ObjectInputStream(inStream);
Person p1 = (Person)s1.readObject();
s1.close();
System.out.println(p1);
}
}

ConcurrentHashMap in Java

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class Concurrenthashmap {
	static final int MAGIC_NUMBER = 250000;
	ConcurrentHashMap<Integer, Integer> c = new ConcurrentHashMap<Integer, Integer>();
	class searchClass implements Runnable
	{
		int id;
		public searchClass(int id) {
			this.id = id;
		}
		
		@Override
		public void run() {
			Integer i = new Integer(MAGIC_NUMBER);
			while(true)
			{
				try {
					Integer o = c.remove(i);
					if(o != null)
					{
						c.clear();
						System.out.println("Thread " + id + ": Magic Number found. Object id: " + System.identityHashCode(o));
					}
					
					Thread.sleep(10);
				} catch (InterruptedException e) {
					return;
				}
			}
		}
	}
	
	public Concurrenthashmap() {
		Thread [] threads = new Thread[6];
		int i = 0;
		for(; i < 4; i++)
			threads[i] = new Thread(new searchClass(i + 1));
		threads[i++] = new Thread(new Runnable() {
			@Override
			public void run() {
				Random r = new Random();
				while(true)
				{
					try {
						for(int i = 0; i < 10000; i++)
						{
							int num = r.nextInt();
							c.put(num, num);
						}
						Thread.sleep(10);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		threads[i++] = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true)
				{
					try {
						c.put(MAGIC_NUMBER, MAGIC_NUMBER);
						System.out.println("-->Thread 6: Magic Number Inserted");
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		
		for(int j = 0; j < threads.length; j++)
			threads[j].start();
		
		try {
			Thread.sleep(100000);
		} catch (InterruptedException e) {
		}
		
		for(int j = 0; j < threads.length; j++)
			threads[j].interrupt();
	}

	public static void main(String[] args) {
		new Concurrenthashmap();
	}
}