当前位置: 代码迷 >> JavaScript >> Spring Json View之高速开始(二)
  详细解决方案

Spring Json View之高速开始(二)

热度:323   发布时间:2012-10-31 14:37:32.0
Spring Json View之快速开始(二)

快速开始-用SimpleForm-Controller提交GET/POST请求
?
?Command-Controller提供一个完整的CommandBean,Spring对它提供校验和绑定支持。这个示例在Command-Controller中返回一个Model-Map的Json字符串,json视图返回信息中包含字段错误、全局错误和绑定。支持CommandBean属性类型的转换。

  • 通过formBackingObject方法触发GET请求。
  • 通过onSubmitAction方法出发POST请求。

?

详细信息参见文档


?
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;
        }
}

?

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;
        }

}

?

  • GET-Response
     Status : 200 
     
     Result:
     {"firstname":"Peter","secondname":"Schmitt"}
    
    ?
  • 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!"
    }}
    
    ?


??

快速开始-使用JsonExceptionResolver抛出异常捕获信息的请求

?

实现异常处理是通过异常分析处理分析器来完成:JsonExceptionResolver。你仅仅需要注册一个JsonErrorHandlers或者JsonExceptionHandler操作一个返回信息以便抛出异常。

JsonErrorHandlers 在产生了错误的情况下发响应到客户端。详细信息参见Errorhandling

JsonExceptionHandler 转换java.lang.Exception对象并添加到Json字符串。详细信息参见Exceptionhandling

?

?

Spring ApplicationContext

??

<beans>
    <bean name="viewResolver" 
        class="org.springframework.web.servlet.view.XmlViewResolver" />
    
    <bean name="throwExceptionGetController" 
        class="org.thing.spring.json.controller.ThrowExceptionGetController"/>
        
    <bean id="exceptionResolver" 
        class="org.springframework.web.servlet.view.json.exception.JsonExceptionResolver">
        <property name="exceptionView"><value>jsonView</value></property>
                <property name="errorHandler">
                <list>
                        <ref bean="statusError" />
                        <ref bean="modelflagError" />
                </list>
        </property>
        <property name="exceptionHandler">
                <list>
                        <ref bean="stackTraceExceptionHandler" />
                        <ref bean="exceptionMessageExceptionHandler" />
                </list>
        </property>
        </bean>
    
        <bean name="statusError" 
              class="org.springframework.web.servlet.view.json.error.HttpStatusError"/>
        
        <bean name="modelflagError" 
              class="org.springframework.web.servlet.view.json.error.ModelFlagError"/
        
        <bean name="stackTraceExceptionHandler" 
              class="org.springframework.web.servlet.view.json.exception.StackTraceExceptionHandler"/>
        
        <bean name="exceptionMessageExceptionHandler" 
              class="org.springframework.web.servlet.view.json.exception.ExceptionMessageExceptionHandler"/>
        
</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>Exception-Handling by JsonExceptionResolver</h2>
        <button id="throwException">throw exception</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 myrules = {

        'button#throwException' : function(element){
                element.onclick = function(){
                        new Ajax.Request('exception.json', { 
                                method:'get',
                                parameters: {throwException: 'true'},
                                onFailure: function(transport){
                                var json = transport.responseText.evalJSON();
                                        printResult(transport);
                        }
                        });
                }
        }
        
};
Behaviour.register(myrules);

?

Controller Source

public class ThrowExceptionGetController implements Controller {

        /** Logger for this class and subclasses */
        protected final Log logger = LogFactory.getLog(getClass());

        public ModelAndView handleRequest(HttpServletRequest request,
                        HttpServletResponse response) throws Exception {

                if(request.getParameter("throwException")!= null)
                        throw new Exception("You throw an exeption !");
                
                Map model = new HashMap();
                model.put("exception", "false");

                return new ModelAndView("json1", model);
        }
}
?

Result

  • GET-Response
    Response-Status : 311
    
    {
            "failure":"true",
            "exception.message":"java.lang.Exception: You throw an exeption !",
            "exception.stacktrace":
                            "java.lang.Exception: You throw an exeption !
                            \n\tat org.thing.spring.json.controller.[...]
                            \n\tat org.springframework.web.servlet.mvc.[...]
                            [...]"
    }
    
    ?
  相关解决方案