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

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: