JOBS4TIMES jobs4timesLogo

Describing Spring Controllers and Validations

Agenda :
  1. Introduction
  2. Types of Controllers (5) :
    1. Controller
    2. AbstractCommandController
    3. SimpleFormController
    4. WizardFormController
    5. MultiActionController
  3. Understanding Validators

The most common way to implement the handler in Spring Web MVC application is as a controller.

Types of Controllers

The most commonly used built-in controller types provided by the Spring Web MVC framework are :
  1. Controller
  2. AbstractCommandController
  3. SimpleFormController
  4. WizardFormController
  5. MultiActionController

Controller (I)

The Controller interface declares only one method, i.e., handleRequest(-,-).
public ModelAndView handleRequest(HttpServletRequest request,
              HttpServletResponse response) throws Exception

AbstractCommandController (C)

protected ModelAndView handle(HttpServletRequest request,
                            HttpServletResponse response,
                        Object command, 
                  BindException errors)throws Exception
Working with AbstractCommandController :
login.html
<body>
 <form action="/login.spring" > <br> // / is optional
 User Name : <input type="text" name="userName"> <br>
 Password: <input type="password" name="password"> <br>
 <input type="submit" value="Login">
 </form> 
</body>
LoginController.java
package com.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

public class LoginController extends AbstractCommandController {

LoginModel loginModel;
public void setLoginModel(LoginModel lm){
 loginModel=lm;
}

protected ModelAndView handle(HttpServletRequest request,
		HttpServletResponse response, 
		Object command, 
		BindException errors) throws Exception {

String type = loginModel.getValidate((UserDetails)command);

System.out.println("type : "+type);

if(type==null)
	//return new ModelAndView("/login.html");
	throw new MyException("User details are not valid");
else if(type.equals("admin"))
	return new ModelAndView("/pages/admin.jsp");
else
	return new ModelAndView("/pages/user.jsp");

} //handleRequest

}
LoginModel.java
package com.spring;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class LoginModel {

private JdbcTemplate jdbcTemplate;

public LoginModel(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate=jdbcTemplate;
}

public String getValidate(UserDetails user) {

 String sql="select type from UserDetails where username=\'"
  +user.getUserName()+"\' and password=\'"+user.getPassword()+"\' ";
 
 try{
	return jdbcTemplate.queryForObject(sql, String.class);	
 }catch (EmptyResultDataAccessException e) {
	 return null;
} 

} //getValidate()

}
UserDetails.java
package com.spring;

public class UserDetails {

private String userName;
private String password;

public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}

}
ds-servlet.xml
<beans>

<!-- configure DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
 <value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
 <value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
 <value>lms</value>
</property>
<property name="password">
 <value>scott</value>
</property>
</bean>

<!-- configure JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <constructor-arg>
  <ref local="dataSource" />
 </constructor-arg>
</bean>

<bean id="loginModel" class="com.spring.LoginModel">
 <constructor-arg>
  <ref local="jdbcTemplate"/>
 </constructor-arg>
</bean>

<bean id="loginController" class="com.spring.LoginController">
 <property name="loginModel">
  <ref local="loginModel"/>
 </property>

<!-- configure the command class name -->
 <property name="commandClass">
  <value type="java.lang.Class">com.spring.UserDetails</value>
 </property>

<!-- configure the command name, the name to use 
when binding the instantiated command class to the request -->

 <property name="commandName">
  <value>UserDetails</value>
 </property> 
 
</bean>

<bean id="handlerMapping" 
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
 <props>
  <prop key="/login.spring">loginController</prop>
 </props>
</property>
</bean>

<bean id="handlerExceptionResolver"
 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
  <props>
   <prop key="com.spring.MyException">
    /myError.html
   </prop>
  </props>
 </property>
</bean>

</beans>
web.xml
<web-app>

<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>

</servlet>	
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
  
</web-app>
admin.jsp
Wel come to Admin page <br/>

User Name : <%= request.getParameter("userName") %>
user.jsp
Wel come to User page <br/>

User Name : <%= request.getParameter("userName") %>
myError.html
<body>
A simple test error page <br>
User details are not valid   
</body>

AbstractCommandController can bind the request data to the command object properties.
We are using UserDetails class as a command class.

Understanding Validators

step 1 : write a validator class
public boolean supports(Class c)
public void validate(Object target, Errors errors)
public boolean supports(Class c) {
return c.equals(UserDetails.class); 
}
step 2 : Associate the Validator to the Controller
<bean id="loginController" class="com.spring.LoginController">
 <property name="loginModel">
  <ref local="loginModel"/>
 </property>

<!-- configure the command class name -->
 <property name="commandClass">
  <value type="java.lang.Class">com.spring.UserDetails</value>
 </property>

<!-- configure the command name, the name to use 
when binding the instantiated command class to the request -->

 <property name="commandName">
  <value>UserDetails</value>
 </property>
 
 <property name="validator">
 <bean class="com.spring.UserValidator"/>
 </property> 
 
</bean>

Working with Validators

login.html
<form action="login.spring" > <br> 
 User Name : <input type="text" name="userName"> <br>
 Password: <input type="password" name="password"> <br>
 <input type="submit" value="Login">
 </form> 
UserValidator.java
package com.spring;

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

public class UserValidator implements Validator {

public boolean supports(Class c) {
return c.equals(UserDetails.class); 
}

public void validate(Object target, Errors errors) {
UserDetails user=(UserDetails)target;


ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", 
	"field.required", "The userName field cannot be empty<br>");

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
		"field.required", "The password field cannot be empty<br>");

if(user.getUserName()!= null && !user.getPassword().equals("") 
                             && user.getPassword().length()<5){
                             
  errors.rejectValue("password", "field.minlength", 
                  new Object[]{Integer.valueOf(5)},
                 "The password must contain minimum 5 characters.<br>");
}//if

} //validate
} //class
LoginController.java
package com.spring;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

public class LoginController extends AbstractCommandController {

LoginModel loginModel;
public void setLoginModel(LoginModel lm){
 loginModel=lm;
}

protected ModelAndView handle(HttpServletRequest request,
		HttpServletResponse response, 
		Object command, 
		BindException errors) throws Exception {
	
	
if(errors.hasErrors()){
 System.out.println("Errors in validation");
 PrintWriter out=response.getWriter();
 out.println("errors in data submitted : <br>");
 out.println("no of errors : "+errors.getErrorCount()+"<br>");
 
 out.println("userName fields errors : <br>"); 
 java.util.List<FieldError> errorList=errors.getFieldErrors("userName");
 for(FieldError error:errorList)
  out.println(error.getDefaultMessage());
 
 out.println("password fields errors : <br>"); 
 errorList=errors.getFieldErrors("password");
 for(FieldError error:errorList)
 out.println(error.getDefaultMessage());
 
 return null;
}
	
	

String type = loginModel.getValidate((UserDetails)command);

System.out.println("type : "+type);

if(type==null)
	//return new ModelAndView("/login.html");
	throw new MyException("User details are not valid ..");
else if(type.equals("admin"))
	return new ModelAndView("/pages/admin.jsp");
else
	return new ModelAndView("/pages/user.jsp");

} //handleRequest

}
LoginModel.java
package com.spring;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class LoginModel {

private JdbcTemplate jdbcTemplate;

public LoginModel(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate=jdbcTemplate;
}

public String getValidate(UserDetails user) {

 String sql="select type from UserDetails where username=\'"
 +user.getUserName()+"\' and password=\'"+user.getPassword()+"\' ";
 
 try{
	return jdbcTemplate.queryForObject(sql, String.class);	
 }catch (EmptyResultDataAccessException e) {
	 return null;
} 

} //getValidate()

}
UserDetails.java
package com.spring;

public class UserDetails {

private String userName;
private String password;

public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}

}
MyException.java
package com.spring;

public  class MyException extends RuntimeException {

	public MyException(String s) {
		super(s);
	}
}
admin.jsp
Wel come to Admin page <br/>

User Name : <%= request.getParameter("userName") %>
user.jsp
Wel come to User page <br/>

User Name : <%= request.getParameter("userName") %>
myError.html
A simple test error page <br>
User details are not valid  
ds-servlet.xml
<beans>

<!-- configure DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
 <value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
 <value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
 <value>lms</value>
</property>
<property name="password">
 <value>scott</value>
</property>
</bean>

<!-- configure JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <constructor-arg>
  <ref local="dataSource" />
 </constructor-arg>
</bean>

<bean id="loginModel" class="com.spring.LoginModel">
 <constructor-arg>
  <ref local="jdbcTemplate"/>
 </constructor-arg>
</bean>

<bean id="loginController" class="com.spring.LoginController">
 <property name="loginModel">
  <ref local="loginModel"/>
 </property>

<!-- configure the command class name -->
 <property name="commandClass">
  <value type="java.lang.Class">com.spring.UserDetails</value>
 </property>

<!-- configure the command name, the name to use 
when binding the instantiated command class to the request -->

 <property name="commandName">
  <value>UserDetails</value>
 </property>
 
 <property name="validator">
 <bean class="com.spring.UserValidator"/>
 </property> 
 
</bean>

<bean id="handlerMapping" 
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
 <props>
  <prop key="/login.spring">loginController</prop>
 </props>
</property>
</bean>


<bean id="handlerExceptionResolver"
 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
  <props>
   <prop key="com.spring.MyException">
    /myError.html
   </prop>
  </props>
 </property>
</bean>

</beans>
web.xml
<web-app>	

<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>

</servlet>	
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
  
</web-app>
result :
errors in data submitted : 
no of errors : 2
userName fields errors : 
The userName field cannot be empty
password fields errors : 
The password field cannot be empty

SimpleFormController

home.jsp
<html>
<body>
<a href="addEmployee.spring">Add Employee</a>
</body>
</html>
addEmployee.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<body>
<form:errors path="EmpDetails.name"/> <br> <br>
<form:errors path="EmpDetails.eno"/>

<form action="addEmployee.spring" method="post"> 
<pre>
Employee Number : <input type="text" name="eno"/>
Employee Name : <input type="text" name="name"/>
Employee Salary : <input type="text" name="salary"/>
Employee Address : <input type="text" name="address"/>
Employee JoinDate : <input type="text" name="doj"/>
 <input type="submit" value="Add Employee"/>
</pre>
</form>

</body>
</html>
addEmployeeSuccess.jsp
<html>
<body>
Employee details added Successfully
</body>
</html>
AddEmployeeController.java
package com.form;

import org.springframework.web.servlet.mvc.SimpleFormController;

public class AddEmployeeController extends SimpleFormController {

EmployeeServices employeeServices;

public void setEmployeeServices(EmployeeServices employeeServices){
 this.employeeServices=employeeServices;
 System.out.println("setEmployees from controller");
}
public void doSubmitAction(Object command) throws Exception{
	employeeServices.create((EmpDetails)command);
	System.out.println("doSubmitAction from controller");
}

}
EmpValidator.java
package com.form;

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

public class EmpValidator implements Validator {

public boolean supports(Class c) {
 boolean flag=c.equals(EmpDetails.class);
 return flag;
}

public void validate(Object target, Errors errors) {
 EmpDetails empDetails=(EmpDetails)target;
 
 ValidationUtils.rejectIfEmptyOrWhitespace(errors,
   "name", "fiels.required","The name field cannot be empty");

if(empDetails.getEno()<10){
 errors.rejectValue("eno", "field.minvalue",
  new Object[]{Integer.valueOf(9)},"The deptno should be greater than 9");
 }
 else if(empDetails.getEno() > 99){
	errors.rejectValue("eno", "field.maxvalue",
	new Object[]{Integer.valueOf(99)},"The deptno should be less than 99");
 }
 
 System.out.println("Emp Validator");
}//validate

} //class
EmployeeServices.java
package com.form;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;

public class EmployeeServices {

private JdbcTemplate jdbcTemplate;
public EmployeeServices(JdbcTemplate jdbcTemplate){
 this.jdbcTemplate=jdbcTemplate;
}

public void create(final EmpDetails user) {

jdbcTemplate.update("insert into emp values(?,?,?,?,?)", 
 new PreparedStatementSetter(){

public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, user.getEno());
ps.setString(2, user.getName());
ps.setString(3, user.getAddress());
ps.setDouble(4, user.getSalary());
ps.setDate(5, new Date(System.currentTimeMillis()));

System.out.println("Emp services update");
}
	
} //PreparedStatementSetter
); //update()

}//create

}
EmpDetails.java
package com.form;

import java.sql.Date;

public class EmpDetails {
	
private int eno;
private String name,address;
private double salary;
private Date date;

public int getEno() {
	return eno;
}
public void setEno(int eno) {
	this.eno = eno;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getAddress() {
	return address;
}
public void setAddress(String address) {
	this.address = address;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public Date getDate() {
	return date;
}
public void setDate(Date date) {
	this.date = date;
}

}
ds-servlet.xml
<beans>

<!-- configure DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
 <value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
 <value>jdbc:oracle:thin:@localhost:1521:xe</value>
</property>
<property name="username">
 <value>lms</value>
</property>
<property name="password">
 <value>scott</value>
</property>
</bean>

<!-- configure JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <constructor-arg>
  <ref local="dataSource" />
 </constructor-arg>
</bean>

<bean id="empServices" class="com.form.EmployeeServices">
 <constructor-arg>
  <ref local="jdbcTemplate"/>
 </constructor-arg>
</bean>

<bean name="/addEmployee.spring" class="com.form.AddEmployeeController">
 <property name="employeeServices">
  <ref local="empServices"/>
 </property>
 
 <property name="commandClass">
  <value type="java.lang.Class">com.form.EmpDetails</value>
 </property>
 
 <property name="commandName">
  <value>EmpDetails</value>
 </property>
 
 <property name="validator">
  <bean class="com.form.EmpValidator"/>
 </property>
 
 <property name="sessionForm" value="false"/>
 
 <property name="formView">
  <value>/addEmployee.jsp</value>
 </property>
 
 <property name="successView">
  <value>/addEmployeeSuccess.jsp</value>
 </property> 
 
</bean>

</beans>
web.xml
<web-app>

<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>

</servlet>
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
  
</web-app>
http://localhost:8001/spring/home.jsp
Result :
setEmployees from controller
Emp Validator
Emp services update
doSubmitAction from controller

WizardFormController

registration1.html
<html>
<body>
<form name="form1"  action="registration.spring" method="post">
<table border="0" align="left">
<tr>
<td colspan="2">
<div align="center"><strong>Registration Step 1 :</strong> </div>
</td>
</tr>
<tr><td>  </td><td>   </td></tr>
<tr>
<td>User Name :</td>
<td><input type="text" name="uname" id="uname"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Re-Password :</td>
<td><input type="text" name="repass" id="repass"></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr><td>  </td><td>   </td></tr>

<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Next >">
</div></td> 
</tr>
</table>
<input type="hidden" name="_page" value="1">
</form>
</body>
</html>
registration2.html
<html>
<body>
<form name="form1"  action="registration.spring" method="post">
<table border="0" align="left" width="45%">
<tr>
<td colspan="2">
<div align="center"><strong>Registration Step 2 :</strong> </div>
</td>
</tr>
<tr><td>  </td><td>   </td></tr>
<tr>
<td>First Name :</td>
<td><input type="text" name="fname" id="fname"></td>
</tr>
<tr>
<td>LastName :</td>
<td><input type="text" name="lname" id="lname"></td>
</tr>
<tr>
<td>Middle Name :</td>
<td><input type="text" name="mname" id="mname"></td>
</tr>
<tr>
<td>DOB :</td>
<td><input type="text" name="dob" id="dob"></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Phone :</td>
<td><input type="text" name="phone" id="phone"></td>
</tr>
<tr><td>  </td><td>   </td></tr>

<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Next >">
</div></td> 
</tr>
</table>
<input type="hidden" name="_page" value="2">
</form>
</body>
</html>
registrationFinal.html
<html>
<body>
<form name="form1"  action="registration.spring" method="post">
<table border="0" align="left" width="45%">
<tr>
<td colspan="3" align="center">
<div><strong>Registration Final Step  :</strong> </div>
</td>
</tr>
<tr><td>  </td><td>   </td></tr>
<tr>
<td colspan="2"><strong>Address : </strong></td> 
</tr>
<tr>
<td>   Address1 :</td>
<td><input type="text" name="addr" id="addr"></td>
</tr>
<tr>
<td>   Street :</td>
<td><input type="text" name="street" id="street"></td>
</tr>
<tr>
<td>   City :</td>
<td><input type="text" name="city" id="city"></td>
</tr>
<tr>
<td>    State :</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>   Country :</td>
<td><input type="text" name="phone" id="phone"></td>
</tr>
<tr><td>  </td><td>   </td></tr>

<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Finish">
</div></td> 
</tr>
</table>
<input type="hidden" name="_finish" value="Finish">
</form>
</body>
</html>
RegistrationContoller.java
package com.wizard;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

@SuppressWarnings("deprecation")
public class RegistrationController extends AbstractWizardFormController {

private UserDAO userDAO;
public RegistrationController(UserDAO userDAO){
 this.userDAO=userDAO;
}
	
@Override
protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, 
			Object command, 
			BindException exceptions) throws Exception {
UserDetails userDetails=(UserDetails)command;
boolean flag=userDAO.create(userDetails);
if(flag)
 return new ModelAndView("registrationSuccess.jsp");
return new ModelAndView("registrationFail.jsp");
}//processFinish

}
UserDetails.java
package com.wizard;

public class UserDetails {

private String uname,pass,repass,email;
private String fname,lname,mname,dob,mobile,phone;
private String addr,street,city,state,country;
public String getUname() {
	return uname;
}
public void setUname(String uname) {
	this.uname = uname;
}
public String getPass() {
	return pass;
}
public void setPass(String pass) {
	this.pass = pass;
}
public String getRepass() {
	return repass;
}
public void setRepass(String repass) {
	this.repass = repass;
}
public String getEmail() {
	return email;
}
public void setEmail(String email) {
	this.email = email;
}
public String getFname() {
	return fname;
}
public void setFname(String fname) {
	this.fname = fname;
}
public String getLname() {
	return lname;
}
public void setLname(String lname) {
	this.lname = lname;
}
public String getMiddle() {
	return mname;
}
public void setMiddle(String mname) {
	this.mname = mname;
}
public String getDob() {
	return dob;
}
public void setDob(String dob) {
	this.dob = dob;
}
public String getMobile() {
	return mobile;
}
public void setMobile(String mobile) {
	this.mobile = mobile;
}
public String getPhone() {
	return phone;
}
public void setPhone(String phone) {
	this.phone = phone;
}
public String getAddr() {
	return addr;
}
public void setAddr(String addr) {
	this.addr = addr;
}
public String getStreet() {
	return street;
}
public void setStreet(String street) {
	this.street = street;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public String getCountry() {
	return country;
}
public void setCountry(String country) {
	this.country = country;
}

}
UserDAO.java
package com.wizard;

public interface UserDAO {

 boolean create(UserDetails userDetails);

}
UserDAOImpl.java
package com.wizard;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;

public class UserDAOImpl implements UserDAO {

private JdbcTemplate jdbcTemplate;
public UserDAOImpl(JdbcTemplate jdbcTemplate){
 this.jdbcTemplate=jdbcTemplate;
}
	
public boolean create(final UserDetails userDetails) {
System.out.println("create");
int count= jdbcTemplate.update(
 "insert into users values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
 new PreparedStatementSetter(){
  public void setValues(PreparedStatement ps) throws SQLException {
  
   ps.setString(1,userDetails.getUname());
   ps.setString(2,userDetails.getPass());
   ps.setString(3,userDetails.getEmail());
   ps.setString(4,userDetails.getFname());
   ps.setString(5,userDetails.getLname());
   ps.setString(6,userDetails.getMiddle());
   ps.setString(7,userDetails.getDob());
   ps.setString(8,userDetails.getMobile());
   ps.setString(9,userDetails.getPhone());
   ps.setString(10,userDetails.getAddr());
   ps.setString(11,userDetails.getStreet());
   ps.setString(12,userDetails.getCity());
   ps.setString(13,userDetails.getState());
   ps.setString(14,userDetails.getCountry());
	  
  }//setValues()
	
} //PreparedStatementSetter()
); //update	
 return (count==1 || count==Statement.SUCCESS_NO_INFO );
} //create	

}
RegistrationFail.html
<html>
<body>
<b>Registration Process Failed</b>
</body>
</html>
RegistrationSuccess.html
<html>
<body>
<b>Registration Process Success </b>
</body>
</html>
applicationControllers.xml
<beans>

<bean name="/registration.spring" class="com.wizard.RegistrationController">
<constructor-arg>
  <ref bean="userDAO"/>
</constructor-arg>

<property name="commandClass">
 <value type="java.lang.Class">com.wizard.UserDetails</value>
</property>

<property name="commandName">
 <value>UserDetails</value>
</property>

<property name="sessionForm" value="true"/>
<property name="pages">
<list>
 <value>/registration1.html</value>
 <value>/registration2.html</value>
 <value>/registrationFinal.html</value>
</list>
</property>
<property name="allowDirtyForward">
 <value>false</value>
</property>
</bean>

</beans>
applicationDAOs.xml
<beans>

<!-- configure DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="lms" />
<property name="password" value="scott" />
</bean>

<!-- configure JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <constructor-arg>
  <ref local="dataSource" />
 </constructor-arg>
</bean>

<bean id="userDAO" class="com.wizard.UserDAOImpl">
 <constructor-arg>
  <ref local="jdbcTemplate"/>
 </constructor-arg>
</bean>

</beans>
web.xml
<web-app>

<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
  /WEB-INF/applicationControllers.xml
  /WEB-INF/applicationDAOs.xml
 </param-value>
</init-param>
<load-on-startup>0</load-on-startup>

</servlet>	
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
  
</web-app>
create users table in DataBase :
create table users(uname varchar2(15), pass varchar2(15),
                   email varchar2(15), fname varchar2(15),
                   lname varchar2(15),mname varchar2(15),
                   dob varchar2(15), moble varchar2(15),
                   phone varchar2(15),addr varchar2(15),
                   street varchar2(15),city varchar2(15),
                   state varchar2(15),country varchar2(15));
result:
http://localhost:8001/spring/registration.spring

MultiActionController

ArithmeticController.java
package com.multi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class ArithmeticController extends MultiActionController {
	
public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
int op1=Integer.parseInt(request.getParameter("operand1"));
int op2=Integer.parseInt(request.getParameter("operand2"));
int result=op1+op2;
return new ModelAndView("/home.jsp","result",result+"");
}

public ModelAndView subtract(HttpServletRequest request,
		HttpServletResponse response) throws Exception{
int op1=Integer.parseInt(request.getParameter("operand1"));
int op2=Integer.parseInt(request.getParameter("operand2"));
int result=op1-op2;
return new ModelAndView("/home.jsp","result",result+"");
}

}
home.jsp
<html>
<body>
<% if(request.getAttribute("result")!=null) { %>
Result of previous  request (<%= request.getParameter("submit") %>) : 
<b>
<%= request.getParameter("operand1")%>,
<%= request.getParameter("operand2")%> 
is :  <%= request.getAttribute("result")%>
</b>
<%} %>

<form method="post" action="myPath.spring">
Operand 1 : <input type="text" name="operand1"/> <br>
Operand 2 : <input type="text" name="operand2"/> <br>
<input type="submit" name="submit" value="add"/>
<input type="submit" name="submit" value="subtract"/>
</form>

</body>
</html>
<beans>

<bean id="myMethodResolver" 
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
 <property name="paramName" value="submit"/>
</bean>

<bean name="/myPath.spring" class="com.multi.ArithmeticController">
 <property name="methodNameResolver" ref="myMethodResolver"/>
</bean>
</beans>
web.xml
<web-app>

<servlet>
<servlet-name>ds</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>

</servlet>	
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
  
</web-app>

BACK