Category Archives: Spring

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

Eclipse : Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”

If you get this even if you have added requred jars,

Right click on the project and click on Add Spring Nature to this project (If you have installed Spring tools)

JAVA: Registration form with Spring

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>Registration Form</display-name>
	<welcome-file-list>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
  
	<servlet>
		<servlet-name>mvc-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>mvc-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>
	
	<!-- <bean class="sam.reg.util.StudentValidator" /> -->
	
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="resources/Student" />
	</bean>
	
</beans>

Student.properties WEB-INF/classes/resources/Student.properties

required.name.student.name=Student name required

Student.java

package sam.reg.domain;

public class Student {

	private String name;
	private short age;
	private byte gender;
	private String phone;
	private String email;
	private String password;
	private String degree;
	private String department;

	// getters and setters ....
}

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.support.SessionStatus;

import sam.reg.domain.Student;
import sam.reg.util.StudentValidator;

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

	private StudentValidator validator;

	@Autowired
	public void setValidator(StudentValidator validator) {
		this.validator = validator;
	}

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

	// processForm
	@RequestMapping(value = "", method = RequestMethod.POST)
	public String processForm(ModelMap model,
			@ModelAttribute("student") Student student, BindingResult result,
			SessionStatus status) {
		validator.validate(student, result);
		if (result.hasErrors()) {
			return "reg-form";
		} else {
			status.setComplete();
			return "successful";
		}
	}

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

	// department list
	@ModelAttribute("departmentList")
	public List<String> populateDepartmentList() {
		List<String> list = new ArrayList<String>();
		list.add("IT");
		list.add("Management");
		return list;
	}

}

StudentValidator.java

package sam.reg.util;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import sam.reg.domain.Student;

@Component
public class StudentValidator implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		return Student.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object arg0, Errors arg1) {
		Student student = (Student) arg0;
		ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "required.name");
	}

}

reg-form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Student Registration Form</title>

<style type="text/css">
.error {
	color: red;
}
</style>

<script type="text/javascript">
	function clearFields() {
		document.forms["reg-form"]["name"].value = "";
		document.forms["reg-form"]["age"].value = "";
		//document.forms["reg-form"]["gender"].checked = false;
		document.forms["reg-form"]["phone"].value = "";
		document.forms["reg-form"]["email"].value = "";
		document.forms["reg-form"]["password"].value = "";
		document.forms["reg-form"]["degree"].selectedIndex = 0;
		document.forms["reg-form"]["department"].selectedIndex = 0;
	}

	function validateFields() {
		return true;
	}
</script>

</head>
<body>
	<form:form method="POST" commandName="student" name="reg-form"
		onsubmit="return validateFields()">
		<table>
			<tr>
				<td colspan="3"><form:errors path="*" cssClass="error" /></td>
			<tr>
				<!-- NAME -->
			<tr>
				<td></td>
				<td><form:input path="name" /></td>
				<td><form:errors path="name" cssClass="error" /></td>
			<tr>
				<!-- AGE -->
			<tr>
				<td></td>
				<td><form:input path="age" /></td>
				<td><form:errors path="age" cssClass="error" /></td>
			<tr>
				<!-- GENDER -->
			<tr>
				<td></td>
				<td>
				<form:radiobutton path="gender" value="0" label="Female" />
				<form:radiobutton path="gender" value="1" label="Male" />				
				</td>
				<td></td>
			<tr>
				<!-- PHONE -->
			<tr>
				<td></td>
				<td><form:input path="phone" /></td>
				<td><form:errors path="phone" cssClass="error" /></td>
			<tr>
				<!-- EMAIL -->
			<tr>
				<td></td>
				<td><form:input path="email" /></td>
				<td><form:errors path="email" cssClass="error" /></td>
			<tr>
				<!-- PASSWORD -->
			<tr>
				<td></td>
				<td><form:input path="password" /></td>
				<td><form:errors path="password" cssClass="error" /></td>
			<tr>
				<!-- DEGREE -->
			<tr>
				<td></td>
				<td><form:select path="degree">
						<form:options items="${degreeList}" />
					</form:select></td>
				<td></td>
			<tr>
				<!-- DEPARTMENT -->
			<tr>
				<td></td>
				<td><form:select path="department">
						<form:options items="${departmentList}" />
					</form:select></td>
				<td></td>
			<tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Submit" /> <input
					type="button" value="Clear" onclick="clearFields()" /></td>
				<td></td>
			<tr>
		</table>
	</form:form>
</body>
</html>

References
Mkyong

Spring: MVC

Eclipse Project
MySpringMVC

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>MySpringMVC</display-name>
	<welcome-file-list>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

springmvc-servlet.xml

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

	<context:component-scan base-package="com.sam.test.controllers" />
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/views/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

DogController.java

package com.sam.test.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DogController {

	@RequestMapping(value="test")
	public String test() {
		return "test";
	}	
}

test.jsp(nothing interesting, just a jsp)

<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
    <jsp:directive.page language="java"
        contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" />
    <jsp:text>
        <![CDATA[ <?xml version="1.0" encoding="ISO-8859-1" ?> ]]>
    </jsp:text>
    <jsp:text>
        <![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
    </jsp:text>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>TEST</title>
</head>
<body>
TEST PAGE
</body>
</html>
</jsp:root>

Copy all jars from following directories to /WEB-INF/lib
spring-framework-3.1.0.RELEASE\dist
and
spring-framework-3.1.0.RELEASE\projects\spring-build\lib\ivy

Java : Spring simple 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>

Java : Spring basics

Download Spring 3.0 RELEASE and copy dist/* and commons-logging.jar to Eclipse project class-path.

There are two ways to Instantiate Spring IoC container
– ClassPathXmlApplicationContext
– FileSystemXmlApplicationContext

Let’s use ClassPathXmlApplicationContext, the config xml will be loaded from the class path.

HelloSpring3.java

package sam.spring;

public class HelloSpring3 {
	public void sayHello() {
		System.out.println("Hello Spring 3");
	}
}

Driver.java

package sam.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Driver {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"HelloSpring3.xml");
		HelloSpring3 hs3 = (HelloSpring3) context.getBean("helloBean");
		hs3.sayHello();
	}

}

HelloSpring3.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="helloBean" class="sam.spring.HelloSpring3" />

</beans>

Output

Mar 06, 2012 4:43:08 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@8ff4cf: startup date [Tue Mar 06 16:43:08 IST 2012]; root of context hierarchy
Mar 06, 2012 4:43:08 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [HelloSpring3.xml]
Mar 06, 2012 4:43:09 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@63a8af: defining beans [helloBean]; root of factory hierarchy
Hello Spring 3