JAVA: Registration Form With Spring and Hibernate

Not working 😀

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>StudentReg</display-name>
	<welcome-file-list>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
  
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/config/spring-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
  
</web-app>

spring-config.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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="sam.reg" />
	
	<mvc:annotation-driven />

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="order" value="1"/>
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
	
	<import resource="db-config.xml" />
	      
</beans>

db-config.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://localhost/reg</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value></value>
		</property>
	</bean>
    
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref local="dataSource"/>
		</property>
		<property name="packagesToScan" value="sam.reg.model" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>
    
	<tx:annotation-driven/>
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory"/>
		</property>
	</bean>   

</beans>

Course.java

package sam.reg.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "COURSE")
public class Course {

	private int id;
	private int version;
	private String name;
	private String code;

	@Id
	@GeneratedValue
	@Column(name = "ID")
	public int getId() {
		return id;
	}

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

	@Column(name = "NAME", nullable = false)
	public String getName() {
		return name;
	}

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

	@Column(name = "CODE", nullable = false)
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Version
	@Column(name = "VERSION", nullable = false)
	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	@Override
	public String toString() {
		return this.name;
	}	
	
}

Student.java

package sam.reg.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "STUDENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class Student {

	private int id;
	private int version;
	private String firstName;
	private String lastName;
	private String gender;
	private String email;
	private String password;
	private Set<Course> courses;

	@Id
	@GeneratedValue
	@Column(name = "ID")
	public int getId() {
		return id;
	}

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

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
	public Set<Course> getCourses() {
		return courses;
	}

	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}

	@Column(name = "FIRST_NAME", nullable = false)
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@Column(name = "LAST_NAME", nullable = false)
	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Column(name = "GENDER", nullable = false)
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Column(name = "EMAIL", nullable = false)
	public String getEmail() {
		return email;
	}

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

	@Column(name = "PASSWORD", nullable = false)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Version
	@Column(name = "VERSION", nullable = false)
	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

}

Undergraduate.java

package sam.reg.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(name="ID")
public class Undergraduate extends Student {

	private int id;

	public int getId() {
		return id;
	}

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

PostGraduate.java

package sam.reg.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(name = "ID")
public class PostGraduate extends Student {

	private int id;
	private String field;

	public int getId() {
		return id;
	}

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

	@Column(name = "FIELD")
	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}
}

CourseDao.java

package sam.reg.dao.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import sam.reg.model.Course;

@Repository
public class CourseDao implements sam.reg.dao.CourseDao {

	private HibernateTemplate template;

	@Autowired
	public void setTemplate(SessionFactory factory) {
		this.template = new HibernateTemplate(factory);
	}

	@Override
	public Course save(Course course) {
		template.saveOrUpdate(course);
		return course;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Course> retrieveAll() {
		return template.find("from Course");
	}
}

UndergraduateDao.java

package sam.reg.dao.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import sam.reg.model.Course;

@Repository
public class CourseDao implements sam.reg.dao.CourseDao {

	private HibernateTemplate template;

	@Autowired
	public void setTemplate(SessionFactory factory) {
		this.template = new HibernateTemplate(factory);
	}

	@Override
	public Course save(Course course) {
		template.saveOrUpdate(course);
		return course;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Course> retrieveAll() {
		return template.find("from Course");
	}
}

CourseService.java

package sam.reg.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sam.reg.dao.hibernate.CourseDao;
import sam.reg.model.Course;

@Service
public class CourseService {

	private CourseDao dao;

	@Autowired
	public void setDao(CourseDao dao) {
		this.dao = dao;
	}
	
	@Transactional
	public Course create(Course course) {
		return dao.save(course);
	}

	@Transactional(readOnly = true)
	public List<Course> readAll() {
		return dao.retrieveAll();
	}
}

UndergraduateService.java

package sam.reg.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sam.reg.dao.hibernate.UndergraduateDao;
import sam.reg.model.Undergraduate;

@Service
public class UndergraduateService {

	private UndergraduateDao dao;

	@Autowired
	public void setDao(UndergraduateDao undergraduateDao) {
		this.dao = undergraduateDao;
	}

	@Transactional
	public Undergraduate create(Undergraduate undergraduate) {
		return dao.save(undergraduate);
	}

	@Transactional(readOnly = true)
	public Undergraduate read(int id) {
		return dao.retrieve(id);
	}

	@Transactional(readOnly = true)
	public List<Undergraduate> readAll(int id) {
		return dao.retrieveAll();
	}

	@Transactional
	public Undergraduate update(Undergraduate undergraduate) {
		return dao.save(undergraduate);
	}

	@Transactional
	public void delete(Undergraduate undergraduate) {
		dao.delete(undergraduate);
	}
}

CourseController.java

package sam.reg.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sam.reg.model.Course;
import sam.reg.service.CourseService;

@Controller
@RequestMapping(value = "/course")
public class CourseController {

	private CourseService courseService;

	@Autowired
	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public @ResponseBody String add() {
		Course course = new Course();
		course.setName("test");
		course.setCode("455");
		courseService.create(course);
		return "successfuly added";
	}
	
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	public @ResponseBody String readCount() {		
		return "" + courseService.readAll().size();
	}
}

StudentController.java

package sam.reg.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import sam.reg.model.Course;
import sam.reg.model.Student;
import sam.reg.model.Undergraduate;
import sam.reg.service.CourseService;
import sam.reg.service.UndergraduateService;

@Controller
@RequestMapping(value = "/student")
public class StudentController {

	private CourseService courseService;
	private UndergraduateService undergraduateService;	
	
	@Autowired
	public void setUndergraduateService(UndergraduateService undergraduateService) {
		this.undergraduateService = undergraduateService;
	}

	@Autowired
	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	// initialize form
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String initForm(ModelMap model) {
		Student student = new Undergraduate();
		model.addAttribute("student", student);
		return "reg-form";
	}

	// process form
	@RequestMapping(value = "", method = RequestMethod.POST)
	public @ResponseBody String processForm(ModelMap model,
			@ModelAttribute("student") Undergraduate student, BindingResult result,
			SessionStatus status) {
		undergraduateService.create(student);
		return student.toString();
	}

	// gender
	@ModelAttribute("genderList")
	public List<String> populateGenderList() {
		List<String> list = new ArrayList<String>();
		list.add("Male");
		list.add("Female");
		return list;
	}

	// degree type
	@ModelAttribute("degreeList")
	public List<String> populateDegreeList() {
		List<String> list = new ArrayList<String>();
		list.add("B.Sc.");
		list.add("M.Sc.");
		return list;
	}

	// courses
	@ModelAttribute("courseList")
	public List<Course> populateCourseList() {
		return courseService.readAll();
	}
	
	// test
	
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String test(ModelMap model) {
		Undergraduate student = new Undergraduate();
		student.setFirstName("fiestName");
		student.setLastName("lastName");
		student.setGender("gender");
		student.setEmail("email");
		student.setPassword("password");
		undergraduateService.create(student);
		return "reg-form";
	}
}

reg-form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Registration</title>
</head>
<body>
	<h3>Registration Form</h3>

	<form:form commandName="student" name="reg-form" method="POST">

		<table>
			<tr>
				<td></td>
				<td></td>
				<td></td>
			</tr>
			<tr>
				<td>First Name</td>
				<td><form:input path="firstName" /></td>
				<td></td>
			</tr>
			<tr>
				<td>Last Name</td>
				<td><form:input path="lastName" /></td>
				<td></td>
			</tr>
			<tr>
				<td>Gender</td>
				<td><form:select path="gender">
						<form:options items="${genderList}" />
					</form:select></td>
				<td></td>
			</tr>
			<tr>
				<td>Email</td>
				<td><form:input path="email" /></td>
				<td></td>
			</tr>
			<tr>
				<td>Password</td>
				<td><form:input path="password" /></td>
				<td></td>
			</tr>
			<tr>
				<td>Degree type</td>
				<td><select name="degreeType">
						<c:forEach var="dType" items="${degreeList}">
							<option value="${dType}">${dType}</option>
						</c:forEach>
				</select></td>
				<td></td>
			</tr>
			<!--<tr>
				<td>Courses</td>
				<td><select name="crs">
						<c:forEach var="course" items="${courseList}">
							<option value="${course.name}">${course.name}</option>
						</c:forEach>
				</select></td>
				<td></td>
			</tr>
			 -->
			<tr>
				<td>Courses</td>
				<td><form:checkboxes items="${courseList}" path="courses" /> </td>
				<td></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Submit" /><input type="button"
					value="Clear" /></td>
				<td></td>
			</tr>
		</table>

	</form:form>


</body>
</html>

					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: