Quickstart - GET/POST request with SimpleForm Controller

The Command Controller emits a filled CommandBean. Validating and binding is supported by Spring.

The Json view response is the Json string of the model map created in the Controller. Field, binding and global errors are included in the Json view response. Even the type converting of CommandBean-Properties is supported.

  • The GET request is hitting the formBackingObject method.
  • The POST request is hitting the onSubmitAction method.

For further information see the Documentation

The following code from the [ Demo application] shows all the code required to define a simple Json POST controller and using it from a button on a form

Spring ApplicationContext

<beans>
    <bean name="simpleJsonPostFormController" 
         class="org.thing.spring.json.controller.SimpleJsonPostFormController">
            <property name="commandClass">
                <value>org.thing.spring.json.controller.SpringJsonForm</value>
            </property>
        <property name="formView"><value>jsonView</value></property>
        <property name="successView"><value>jsonView</value></property>
    </bean>
    <bean name="urlMapping" 
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/hello.json">simpleJsonPostFormController</prop>
           </props>
        </property>
    </bean>
    <bean name="viewResolver" 
        class="org.springframework.web.servlet.view.XmlViewResolver" />
</beans>

Spring view.xml

<beans>
    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
            <property name="jsonErrors">
                <list>
                        <ref bean="statusError" />
                        <ref bean="modelflagError" />
                </list>
        </property>
    </bean>
    
    <bean name="statusError" 
          class="org.springframework.web.servlet.view.json.error.HttpStatusError">
          <property name="errorCode"><value>311</value></property>
    </bean>
    <bean name="modelflagError" 
          class="org.springframework.web.servlet.view.json.error.ModelFlagError">
          <property name="name"><value>failure</value></property>
          <property name="value"><value>true</value></property>
    </bean>
        
</beans>

form.html

<head>
        <title>
                First Test Spring Json Demo
        </title>
        <script type="text/javascript" src="script/prototype.js"></script>
        <script type="text/javascript" src="script/behaviour.js"></script>
        <script type="text/javascript" src="script/behaviour-roles.js"></script>
        <meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type"/>
</head>
</head>
<body>
        <h1>Spring JSON DEMO</h1>
        <h2>Spring Ajax Post (SimpleFormControler and CommandController)</h2>
        <form method="post" id="form">
                <input id="placeofbirth" type="text" name="placeofbirth" ><br>
                <input id="birthday" type="text" name="birthday" ><br/>
                <br/>
                <b>place of birth : </b><span id="t_placeofbirth"></span><br/>
                <b>birthday : </b><span id="t_birthday"></span><br/>
        
        </form>
        <br/>
        <span id ="error" ></span>
        <br/>
        <button id="clearData">clear name</button>
        <<button id="sfc_postData">send data to SimpleFormController</button>
</body>

JavaScript behaviour-roles.js

var printResult = function(transport){
                var result = 
                        "Status : " + transport.status
                        + "\n"
                        + "\n"
                        + "Json-Result:"
                        + "\n" + transport.responseText;
                alert(result);
};
var addErrors = function(transport){
        var json = transport.responseText.evalJSON();
        
        var error = "Errorhandler Info: </br>"
        + "failture: " + json.failure +"</br>"
        + "status : + " + transport.status +"</br>"
        +"</br>"
        +"Spring Errorhandling: </br>"
        + "hasGlobalErrors : " + json.hasGlobalErrors +"</br>"
        + "</br>"
        + "hasFieldErrors : " + json.hasFieldErrors +"</br>";
        if(json.fielderrors.birthday)
                error = error + "birthday : " + json.fielderrors.birthday +"</br>";
        if(json.fielderrors.placeofbirth)
                error = error + "placeofbirth : " + json.fielderrors.placeofbirth +"</br>";
        
        $('error').innerHTML = error;
};
var myrules = {
        'button#clearData' : function(element){
                element.onclick = function(){
                        $('t_placeofbirth').innerHTML = '';
                        $('t_birthday').innerHTML = '';
                        $('error').innerHTML = '';
        },
        'button#sfc_postData' : function(element){
        
            new Ajax.Request('hello1.json', { 
                                method:'get',
                                onSuccess: function(transport){
                                        var json = transport.responseText.evalJSON();
                                        printResult(transport);
                                $('placeofbirth').value = json.command.placeofbirth;
                                $('birthday').value = json.command.birthday;
                        },
                        onFailure: function(transport){
                                var json = transport.responseText.evalJSON();
                                        printResult(transport);
                                        addErrors(transport);
                        }
                        
                        }); 
            
                element.onclick = function(){
                        new Ajax.Request('hello1.json', { 
                                method:'post',
                                parameters: $('form').serialize(false),
                                onSuccess: function(transport){
                                        var json = transport.responseText.evalJSON();
                                        printResult(transport);
                                        $('t_placeofbirth').innerHTML = json.command.placeofbirth;
                                $('t_birthday').innerHTML =  json.command.birthday;
                                $('error').innerHTML = '';
                        },
                        onFailure: function(transport){
                                var json = transport.responseText.evalJSON();
                                        printResult(transport);
                                        addErrors(transport);
                        }
                        
                        });
                }
        }
};
Behaviour.register(myrules);

CommandBean

public class SpringJsonForm {

        private String placeofbirth;
        private Date birthday;
        
        
        public String getPlaceofbirth() {
                return placeofbirth;
        }
        public void setPlaceofbirth(String placeofbirth) {
                this.placeofbirth = placeofbirth;
        }
        public Date getBirthday() {
                return birthday;
        }
        public void setBirthday(Date birthday) {
                this.birthday = birthday;
        }
}

Controller Source

public class SimpleJsonPostFormController extends SimpleFormController {

        protected void initBinder(HttpServletRequest request,  ServletRequestDataBinder binder) throws Exception{
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
                binder.registerCustomEditor(Date.class, editor);
        }

        @Override
        protected Object formBackingObject(HttpServletRequest request)
                        throws Exception {
                SpringJsonForm bean = new SpringJsonForm();
                bean.setBirthday(new Date());
                bean.setPlaceofbirth("Sydney");
                return bean;
        }

        public void onSubmitAction(Object command, BindException errors) {
                SpringJsonForm bean = (SpringJsonForm) command;
        }

}

Result

  • GET-Response
     Status : 200 
     
     Result:
     {"command":{"birthday":"14-04-2009","placeofbirth":"Sydney"}}
  • POST Response
    Response-Status : 311
    
    {"command":{
                "birthday":"30-01-2008",
                "placeofbirth":"Sydney"
               },
     "failure":"true",
     "hasGlobalErrors":"true",
     "globalerrors": ["errormessage1","errormessage2"],  
     "hasFieldErrors":"true",
     "fielderrors":{
                 "birthday":"Please enter a valide date!"
    }}