SimpleFormController in Spring with Validator


SimpleFormController


How will be provide valid form data to the Controller in Spring , answer is SimpleFormController.
This class provided very customizable or simple way to process form data in spring. Which is describe diagrammatically below.




The SimpleFormController creates and populates a command bean, which contains all the parameters from the form as JavaBean properties accessible via getters and setters. The command bean will be validated if validation is enabled, and if no errors are found, the command bean will be processed. Otherwise, the original form page will be shown again, this time with the errors from validation.

Septs:
1.       Create new project and include Spring MVC library
2.       Create input page like below



Spring Form tags is used for input designing

Index.jsp
<%@taglib  uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
    <body bgcolor="cyan">
        <h2 style="background-color: yellow">Enter User Details</h2>
        <form:form commandName="reg" method="POST">
           User Name: <form:input path="username"/><font color="red">
               <form:errors path="username"/></font><br>
           Password: <form:password path="password"/><font color="red">
           <form:errors path="password"/></font><br>
           First Name: <form:input path="fname"/><br>
           Last Name: <form:input path="lname"/><br>
           Gender: <form:radiobutton path="gender" value="male"/>Male
               <form:radiobutton path="gender" value="female"/>Female<br>
               Country :<form:select path="country" size="3" >
                       <form:option value="india">India</form:option>
                       <form:option value="india">USA</form:option>
                       <form:option value="india">Australia</form:option>
                   </form:select><br>
                   Address: <form:textarea path="addr"/><br>
                       Select any :<form:checkbox path="cb" value="checkbox1"/>
                       Check Box1
                       <form:checkbox path="cb" value="checkbox2"/>
                       Check Box2<br>
            <input type="submit" value="submit"/>
        </form:form>
    </body>
</html>
3.       Create Command Bean class

public class Registration {
   private String username;
    private String password;
    private String fname;
    private String lname;
    private String gender;
    private String country;
    private String addr;
    private String cb;

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public String getCb() {
        return cb;
    }

    public void setCb(String cb) {
        this.cb = cb;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getGender() {
        return gender;
    }

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

    public Registration() {
    }

    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 getPassword() {
        return password;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

4.       Create Controller class by sub classing SimpleFormController

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

public class RegistrationFormController extends SimpleFormController {

@Override
    protected ModelAndView onSubmit(Object command) throws Exception {

        Registration reg=(Registration)command;

        String uname=reg.getUsername();
        String fname=reg.getFname();
        String lname=reg.getLname();

        String gender=reg.getGender();
        String country=reg.getCountry();
        String cb=reg.getCb();
        String addr=reg.getAddr();

         ModelAndView mv = new ModelAndView(getSuccessView());

          mv.addObject("uname",uname);
          mv.addObject("fname",fname);
          mv.addObject("lname",lname);
          mv.addObject("gender",gender);
          mv.addObject("country",country);
          mv.addObject("cb",cb);
          mv.addObject("addr",addr);

        return mv;
    }

}

5.       Create registration validator by implementing Validator interface



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

public class registrationValidator implements Validator
{

    public boolean supports(Class cl) {
        return Registration.class.isAssignableFrom(cl);

    }

    public void validate(Object ob, Errors errors) {
       Registration reg=(Registration)ob;
       if (reg.getUsername() == null || reg.getUsername().length() == 0) {

            errors.rejectValue("username", "error.empty.username");
        }

       else if (reg.getPassword() == null || reg.getPassword().length() == 0) {
            errors.rejectValue("password", "error.empty.password");

        }

    }

}
6.       Create properties file messages.properties

error.empty.username=Please Enter User name
error.empty.password=Please Enter Password

7.       Configure above all beans in configuration file
<beans>
  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean id="urlMapping"            class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">registrationController</prop>
            </props>
        </property>
    </bean>

    <bean id="registrationValidator" class="registrationValidator"/>

    <bean id="registrationController" class="RegistrationFormController">

        <property name="sessionForm"><value>false</value></property>

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

        <property name="commandClass" value="Registration"></property>

        <property name="validator"><ref bean="registrationValidator"/></property>
        <property name="formView"><value>index</value></property>

        <property name="successView"><value>success</value></property>

    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>
   

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

</beans>

8.       Output page

success.jsp

<body bgcolor="DDDDDD">
        <h1>Details of User</h1>
        <h2>
            User Name: ${uname}<br>
            First Name: ${fname}<br>
            Last Name: ${lname}<br>
            Gender: ${gender}<br>
            Country: ${country}<br>
            Address: ${addr}<br>
            Selected Check box: ${cb}
        </h2>

    </body>

9.       Run project



Output



No comments:

Post a Comment