Friday, October 22, 2010

Spring with in a Day Part-6

How to Deals with the Form & Command bean object in Spring
-----------------------------------------------------------------------
In order to deals with the parameters in the query string or with the fields in the form we must use Command bean in as based application.



AbstructCommandController
----------------------------------------------------
i. AbstructCommandController implements the Controller interface. This class contains the code to deal with the command bean object.
ii. To deal with the above query string in our form we must provide the command bean support pone and ptwo properties.

package pack;
public class OCBean {
String pone;
String ptwo;
//add setter and getter methods
}

iii. Capture the data and putting the data ion our command bean object is call binding. Spring code used the setter methods provided in the bean class to bind the data in the command bean object.

JSP code (form.html):-
< %@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %>
< %@ taglib prefix=”spring” uri=”http://www.springframework.org/tags” %>
< %@ page isELIgnored=”true” %>
< form action=”/fh.htm” method=”post”>
Field One < input type=”text” name=”pone”/>< br>
Field Two < input type=”text” name=”ptwo”/>< br>
< input type=”submit” value=”Send” />< br>
< /from>

iv. For dealing with the above from or to deal with the parameters of the query string in the URL is going bellow –
http://localhost:8080/swapp/fh.htm?pone=AAA&ptwo=BBB
we must use the command bean class shown above (OCBean.java)
v. For using the command bean we must provide the controller classes as the subclass of AbstructCommandController.

package pack;
public class OCController extends AbstructCommandController {
public OCController() {
this.setCommandName(“ocb”)_;
this.setCommandClass(pack.OCBean.class);
}
Protected ModelAndView handle (HttpServletRequest request,
HttpServletReqponse response, Object cmd, BindException be)
throws Exception {
OCBean cb=(OCBean) cmd;
System.out.println(“pone=”+cb.getPone());
System.out.println(“ptwo=”+cb.getPtwo());
return null;
}
}

vi. When form will be submitted the spring code that is part of AbstructCommandController takes care of –
 Capturing data provided by user
 Creates the command bean object
 Bind the data to the command bean object by calling the setter.
 Calls the handle() method.



BindException
-------------------------------
We must add the error code with the error messages in properties files as shown bellow –resone.properties file –
typeMismatch.ocb.pone = Field must be integer
typeMismatch.ocb.ptwo = Field must be float
err.one = Error message one
err.two = Error message two

applicationContext.xml file –
< bean id=”messageSource”
Class=”org.springframework.context.support.ResouceBundleMessageSource”>
< property name=”basename” value=”resone”>< /property>
< /bean>

spring-servlet.xml file –
< bean name=”/fh.htm” class=”pack.OCController”>< /bean>

package pack;
public class OCBean {
int pone;
float ptwo;
//add setter and getter methods
}
package pack;
public class OCController extends AbstructCommandController {
public OCController() {
this.setCommandName(“ocb”);
this.setCommandClass(pack.OCBean.class);
}
protected ModelAndView handle (HttpServletRequest reuest,
HttpServletResponse response, Object cmd, BindException be)
throws Exception {
OCBean cb=(OCBean) cmd;
Map map = be.getModel();
be.rejectValue(“pone”,”err.one”,”default message”);
be.rejectValue(“ptwo”,”err.two”,”default message”);

be.rejectValue(“ptwo”,”err.thr”,”default message”);
System.out.println(“ec=>”+be.getErrorCount());
System.out.println(“ec=>”+be.getAllErrors());
ModelAndView mav=new ModelAndView();
mav.setViewName(“despRes”);
mav.addAllObjects(map);
return mav;
}
}

Explanation for some statements –
----------------------------------------------------
Map map = be.getModel();
It returns a Map object that contains the command bean object and BindingResult object.



be.rejectValue(“ptwo”, “err.two”, “default message”);
add error and error message in the model. It search the error code in property file for error message. If error message available in property file for the error code it fetch that message in the error object. If it not available then it adds the default error message for the error code.




JSP code (dispRes.jsp):-
< %@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %>
< %@ taglib prefix=”spring” uri=”http://www.springframework.org/tags” %>
< %@ page isELIgnored=”true” %>
< c:out value=”${requestScope.ocb.pone}” />< br>
< c:out value=”${requestScope.ocb.ptwo}” />< br>
< spring:bind path=”ocb.pone”>
< c:forEach var=”emsg” items=”${status.errorMessages}”>
< c:out value=”${emsg}”/>< br>
< /c:forEach>
< /spring:bind>
< spring:bind path=”ocb.ptwo”>
< c:forEach var=”emsg” items=”${status.errorMessages}”>
< c:out value=”${emsg}”/>< br>
< /c:forEach>
< /spring:bind>

The bind tag creates a variable named status and this variable point to BindStatus object. The BindStatus object contains the property called errorMessage and errorMessages.




Example:
---------------------
JSP code (urform.html):-
< %@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %>
< %@ taglib prefix=”spring” uri=”http://www.springframework.org/tags” %>
< %@ page isELIgnored=”true” %>
< form method=”post” action=”ru.html”>
Name: < input type=”text” name=”username”>< /br>
Age: < input type=”text” name=”age”>< /br>
Weight: < input type=”text” name=”weight”>< /br>
DOB: < input type=”text” name=”dob”>< /br>
URL: < input type=”text” name=”webPg”>< /br>
Contact: < input type=”text” name=”contactNo”>< /br>
< input type=”submit” value=”Register”>< /br>
< /form>




Command Class –
package pack;
public class UserRegCB {
String username;
int age;
float weight;
java.util.URL webPg;
java.util.Date dob;
String contactNo;
//add setter and getter for all properties
}

As part of spring software various property editor classes are provided in the package org.springframework.beans.propertyeditors.

Note:
-----------------
 CustomDateEditor converts String into java Date object.
 ClassEditor converts String into java Class object.
 initBinder() is used to register BindEditor to bind the data to the Bean object.
 BindEditor is used to convert the data object to another object or data type.
 initBinder() is responsible to register CustomEditor with the binder.

spring-servlet.xml file –
< bean name=”/ru.htm” class=”pack.URController”>
< property name=”commandName” value=”urcb”>< /property>
< property name=”commandClass” value=”pack.UserRegCB”>< /property>
< /bean>

package pack;
public class URController extends AbstructCommandController {
protected void initBinder (HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
Binder.registerCustomEditor(Date.class, new CustomDataEditer (
new SimpleDateFormat(“dd/MM/yyyy”),true));
}
protected ModelAndView handle (HttpServletRequest reuest,
HttpServletResponse response, Object cmd, BindException be)
throws Exception {
UserRegCB cb=(UserRegCB) cmd;
System.out.println(“user name=”+cb.getUserName());
Map map = be.getModel();
ModelAndView mav=new ModelAndView();
mav.setViewName(“dispRes”);
mav.addAllObjects(map);
return mav;
}
}

The binder object is responsible for binding the data to command bean by calling the setters. While binding the data it has to convert the string object into appropriate data types. For example, the dob field must be converted as java Date object. For converting data to appropriate type, the PropertyEditors will be used by the binder this is why we have use bind.registerCustomEditor() method.

No comments:

Post a Comment