What is Spring Json View about ?
什么是Spring Json View?
Spring Json-View adds JavaScript Object Notation (json) support to Spring-MVC. It is deeply integrated into the spring mvc-module and can be used with all kind standart-controllers.
In the times of web 2.0 Ajax is a popular way to communicate from Client (Browser) to Server. In the java server-side universum spring-mvc has become a standard web framework. There are a couple of projects which try to connect Spring-MVC and json by a view. One example is the json-lib-ext-spring project.
In our first web 2.0 project we looked for a way to use sping-mvc knowledge for the server-side for the Ajax-request targets. But there was nothing that was satisfying a fastidious sping-mvc developer. So we started to think about a spring json-view which is supporting all spring-mvc features.
Spring json-view 为Spring-MVC提供了对JavaScript Object Notation (json) 的支持,它深入地集成在Spring MVC模块里,能够适用于所有标准的控制器类。
在Web 2.0 Ajax 时代里常见的方式是客户(浏览器)和服务器的交互。在Java服务器端通常把Spring MVC看成是一个标准的web框架。他们尝试通过Spring MVC和Json方式的视图结合成为一个方案,比如Json-Lib-Ext-Spring。
在我们第一个Web2.0工程里我们寻找一种方式使用服务器端Spring-MVC的知识接收和响应Ajax请求。但是没有一个令苛刻的Spring MVC开发者们感到满意。所以我们开始探索Spring Json-View用于支持所有Spring MVC特性。
Status
近况
NEWS
新闻
spring-json 0.1 final released Spring-json 0.1 最终版发布
- Exceptionhandling support added 添加异常处理支持
- Demoapplication updated 修改演示程序
- Documentation and Test updated 修改文档和测试用例
- bugs fixed 修正一些Bug
download 下载
What is the difference?
哪些不同点?
This Spring Json View is deeply integrated into the spring mvc-module. It can be used with all kind of standard controllers which the springmvc supports by default eg. the SimpleFormController.
Spring Json View 深入地集成在Spring MVC模块里。它能够适用于所有的SpringMVC支持(如SimpleFormController)的标准控制器类。
Configuration
配置
It can be configurated by the spring way!
它通过SpringXml方式配置
Binding
绑定
It supports the spring way by converting bean property values for the view. (Please see the initBinder() method of the SimpleFormController)!
它支持用Spring方式把Bean属性转换到View里。(请参见SimpleFormController的initBinder()方法)
Validating
校验
It supports the spring way validation by ValidatorBeans!
它支持用ValidatorBeans Spring 方式的校验
Errorhandling
错误处理
It supports spring way errorhandling including global, field and binding errors!
它支持Spring方式错误处理,包括全局、字段和绑定错误。
Exceptionhandling
异常处理
It supports the spring way exceptionhandling by a JsonExceptionResolver!
它使用 JsonExceptionResolver支持 Spring 方式的异常处理。
This way you are able to swap a "classic" spring application for a web 2.0 application by keeping the backend and just changing the view.
通过它你只要改变视图而不必改变后台编码就能把典型Spring应用转换为Web2.0应用。
Documentation
文档中心
Spring json-view adds JavaScript Object Notation (json) support to Spring-MVC. It gives you the possibility to use spring-mvc as you are used to. Now it enables you to serve data to ajax-based frontends very easy. It provides almost all features you used in, for example, the Spring JstlView.
Basically, it is an implementation of an AbstractView. Now it adds a Spring BindingResult, Field- and GlobalErrors, executes validations and PropertyEditors to convert propertyvalues to a display string. But it also provides some useful features to serve Ajax-Frameworks, for example prototype like the Error Handling. And of course it transforms the model to a Json String.
For a practical example please take a look at the Demo Application.
Spring json-view 为Spring-MVC提供了对JavaScript Object Notation (json) 的支持,它能让你像平时使用spring-mvc一样使用。现在它能够让你的基于Ajax的前端工具更容易提取(服务器端)数据。
基本上,它是通过AbstractView实现的。现在它增加了Spring BindingResult(结果绑定),Field 和GlobalErrors(字段和公共错误信息),完成校验和一个将属性值转换成显示字符串的属性编辑器。但是它也可以提供一些有用的特性为Ajax-Frameworks服务。比如,类似prototype的错误处理。当然还有转换成Json 字符串的Model。
查看演示程序可以获得实用的例子。
Binding
绑定
1.Simple Binding
简单绑定
2.Binding to CommandBean-Property
使用CommandBean-Property绑定
3.Convert all Model Values.
转换所有Model Values.
1.Convert all values in Model-Map by CustomEditor
Model-Map通过CustomEditor转换所有值
2.Convert specific values in Model-Map by CustomEditor
Model-Map通过CustomEditor转换特殊值
Validating
校验
1.Spring MVC validation example
Spring MVC 校验样例
Errorhandling
错误处理
1.Configuration
配置概述
2.HttpStatusError
Http状态错误
3.ModelFlagError
模型标记错误
4.CustomImplementaton of JsonErrorHandler
自主实现的Json错误处理器
Exceptionhandling
异常处理
1.Configuration
配置概述
2.JsonErrorHandler
Json错误处理器
3.JsonExceptionHandler
Json异常处理器
1.ExceptionMessageExceptionHandler
异常消息处理器
2.StackTraceExceptionHandler
堆栈异常处理器
3.CustomImplementaton of JsonExceptionHandler
自定义实现Json异常处理器
Other Configurations
其它配置
1.Convert to all Model Values
转换所有Model Values
2.ContentType
容器类型支持
3.Encoding
编码支持
Binding - Conversion of Datatypes
绑定-数据类型转换
Instruction导论
Simple Binding 简单绑定
Binding to CommandBean-Property 绑定到CommandBean-Property
Convert all Model Values 转换所有Model Values
Convert all values of Model-Map by CustomEditor Model-Map通过CustomEditor转换所有值
Convert specific value in Model-Map by CustomEditor Model-Map通过CustomEditor转换特殊值
1. Instruction
导论
You can implement the binding the way you know it from the Spring Command or FormController. Usually you register a CustomEditor at the ServletRequestDataBinder in the initBinder-method of the controller (see below).
你可以从Spring Command 和FormController中实现你知道的绑定方式。通常你在ServletRequestDataBander中用控制器的初始绑定方法定义一个自定义对象(看下面描述)
You can bind a CustomEditor to
你能绑定的CustomEditor包括
- Global value class types like java.util.Date
- 像java.util.Date普通数据类型的对象
- Properties of the ComandBean located by the CommensBeanUtils-Syntax
- 能按CommensBeanUtils-Syntax匹配ComandBean字段的对象
- And exclusively at Spring Json View: To any other object in the model like those added in the referenceData-method.
- 当然还有Spring Json View中特有的类型:像那些附加referenceData-method的Model中任意其它对象
Attention :
注意:
Spring Json View can't bind properties of a collection of Beans in the following case :
Spring Json View 不能绑定如下例Bean中Collection类型中的属性
Spring provides:
Spring提供的写法:
bean.list.property
The syntax locates all properties of the collection from index 0-n
这个语法是找出conllection中从0-n的所有属性
Spring Json View can locate properties Collection-Beans with EXPIZITE index like:
Spring Json View 能找出像下面这样使用解释型索引的Collection-Beans的属性:
bean.list[0].property
bean.set[1].list[2].property
2. Simple Binding
简单绑定
initBinder Source:
=================
@Override
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);
}
Result:
=======
{"command":{
"birthday":"30-01-2008",
"marriage":"30-01-2008",
"placeofbirth":"Sydney"
}}
3. Binding to CommandBean-Property
使用CommandBean-Property绑定
initBinder Source:
==================
@Override
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, "birthday", editor);
}
Result:
======
{"command":{
"birthday":"30-01-2008",
"marriage":"Wed Jan 30 00:00:00 GMT 2008",
"placeofbirth":"Sydney"
}}
4. Convert all Model Values
转换所有Model的值
Spring Json View does provide the conversion of non CommandBean-Values of the model map. You have to activate
this feature by setting the convertAllMapValues property in the JSONWriter-Bean in the view.xml see
Spring Json View 已经提供 非CommandBean-Values在Model Map 的转换。你可以利用这个特性在view.xml用
You can locate them by registering a CustomEditor for a field starting with (non_commandbean_key).
你能在一个CustomEditor定义的字段利用non_commandbean_key找到它们。
(name_in_model_map_key).property
(key).list[1].property
3.1 Convert all values in Model-Map by CustomEditor
Model-Map通过CustomEditor转换所有值
initBinder Source:
==================
@Override
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);
}
Result:
=======
{"signdate":"30-01-2008",
"command":{
"birthday":"30-01-2008",
"marriage":"30-01-2008",
"placeofbirth":"Sydney"
}}
3.2 Convert specific values in Model-Map by CustomEditor
Model-Map通过CustomEditor转换特殊值
initBinder Source:
==================
@Override
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, "birthday", editor);
binder.registerCustomEditor(Date.class, "(signdate)", editor);
}
Result:
=======
{"signdate":"30-01-2008",
"command":{
"birthday":"30-01-2008",
"marriage":"Wed Jan 30 00:00:00 GMT 2008",
"placeofbirth":"Sydney"
}}
Validation
校验
The Validation of a POST request is very easy. Just register a validator the spring way. Spring json view adds the fielderror to the response json string.
来自Post的请求校验的非常容易。仅仅需要按Spring方式注册一个校验器。Spring Json View 在返回Json字符串数据时增加字段错误处理
Validator
校验器
Write your validator class by implementing the Validator-Interface.
用Validaor-Interface实现一个自己校验器类
public class SpringJsonValidator implements Validator {
public void validate(Object obj, Errors errors) {
SpringJsonForm form = (SpringJsonForm) obj;
if (form.getPlaceofbirth() == null || "".equals(form.getPlaceofbirth())) {
errors.rejectValue("placeofbirth", "error.no.placeofbirth", null, "Placeofbirth required.");
}
}
@Override
public boolean supports(Class clazz) {
return SpringJsonForm.class.equals(clazz);
}
}
Spring ApplicationContext
Configurate the SimpleFormController by adding the validator.
在SimpleFormController中添加校验器
<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>
<property name="validator"><ref bean="validator"/></property>
</bean>
<bean name="validator" class="org.thing.spring.json.controller.SpringJsonValidator"/>
</beans>
Result
Spring Json-View added the fielderror to the json response.
Spring Json View 增加Json response 字段错误提示。
{"command":{
"birthday":"08-02-2008",
"placeofbirth":""
},
"failure":"true",
"hasGlobalErrors":"false",
"hasFieldErrors":"true",
"fielderrors":{
"placeofbirth":"Please enter a a place of birth!"
}}
Errorhandling
错误处理
The errorhandling is triggered after the controller adds some Global- or FieldErrors (the BindingResult) to the model.
错误处理在控制器向Model中增加一些公共或字段级错误(绑定的结果集)后触发。
Configuration 配置
HttpStatusError Http状态错误
ModelFlagError Model标记错误
CustomImplementaton of JsonErrorHandler 自主实现的Json错误处理器
1. Configuration : view.xml
Spring配置文件:view.xml
After the errors (Global- and Field-) have been prepared to be converted into a json-string, all registered JsonErrorHandlers are triggered in the order they were added.
把错误(公共级别的和字段级别的)配置好后转换成一个json字符串,所有注册的Json错误处理器在他们被添加按规则触发。
The following JsonErrorHandlers are implemented:
下列是JsonErrorHadnders的实现:
HttpStatusError
Http状态错误
Sets a new Response-Status by response.setStatus(errorCode); Some Ajax-Frameworks for example
prototypejs trigger the onSuccess (200 - 299) or onFailure (>=300) by ResponseStatusCodes
The Default Code is 311.
用response.setStatus(errorCode)设置一个新返回状态;一些Ajax框架比如
prototype.js中触发成功状态使用返回状态编码是200-299,失败状态使用>=300,
默认编码为311.
ModelFlagError
Model标记错误
Adds a simple key-value-pair to the model. Some Web2.0 Gui-frameworks need a flag to validate a success or failure of the serverside action. Ext for example needs a failure=true or success=true
The Default flag is failure=true
在Model里增加一个简单键值对。一些Web2.0 表现层框架需要一个标记来判断服务器端的操作是否成功或失败。比如Ext框架需要一个failure=true 或者 success=true
默认标记是failure=true
<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"/>
<bean name="modelflagError"
class="org.springframework.web.servlet.view.json.error.ModelFlagError"/>
</beans>
Result:
=======
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!"
}}
2. HttpStatusError
Http状态错误
You can customize the StatusErrorCode added to the response by setting the errorCode property of the HttpStatusError Bean.
你可以在HttpStatusError Bean的错误编码属性里自定义状态错误编码到响应信息里。
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
<property name="jsonErrors">
<list>
<ref bean="statusError" />
</list>
</property>
</bean>
<bean name="statusError"
class="org.springframework.web.servlet.view.json.error.HttpStatusError">
<property name="errorCode"><value>999</value></property>
</bean>
</beans>
Result:
=======
Response-Status : 999
{"command":{
"birthday":"30-01-2008",
"placeofbirth":"Sydney"
},
"hasGlobalErrors":"true",
"globalerrors": ["errormessage1","errormessage2"],
"hasFieldErrors":"true",
"fielderrors":{
"birthday":"Please enter a valide date!"
}}
3. ModelFlagError
Model标记错误
You can customize the key-value-pair added to the model by setting the key- and the value-property of the ModelFlagError Bean.
你可以在ModelFlagError Bean以键值对方式设置到Model里。
<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="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>
Result:
=======
Response-Status : 200
{"command":{
"birthday":"30-01-2008",
"placeofbirth":"Sydney"
},
"failure":"true",
"hasGlobalErrors":"true",
"globalerrors": ["errormessage1","errormessage2"],
"hasFieldErrors":"true",
"fielderrors":{
"birthday":"Please enter a valide date!"
}}
4. Custom implementation of JsonErrorHandler
自定义实现JsonErrorHandler
It is possible to realize some totally different behaviours by implementing the JsonErrorHandler.
你也可以自己实现JsonErrorHandler用一些完全不同的方式重构它。
public class MyErrorHandler implements JsonErrorHandler {
public void triggerError(Map model, RequestContext rc, BindingResult br,
HttpServletRequest request, HttpServletResponse response)
throws Exception{
// Do something ...
}
}
Exceptionhandling
异常处理
The spring json-view is providing an
HandlerExceptionResolver (JsonExceptionResolver) to catch any Exception thrown during a controller action.
Configuration 配置
JsonErrorHandler
JsonExceptionHandler
ExceptionMessageExceptionHandler 异常消息异常处理器
StackTraceExceptionHandler 堆栈异常处理器
CustomImplementaton of JsonExceptionHandler 自定义实现JsonExceptionHandler
1. Configuration : Spring ApplicationContext
配置文件:Spring ApplicationContext
You have to register at least one JsonErrorHandlers or JsonExceptionHandler to manipulate the response in the case of an thrown exception .
你几乎只需要注册一个JsonErrorHandlers 或者 JsonExceptionHandler 就可以来操作函数中的响应以便抛出异常。
Attention:
Register the JsonExceptionResolver in the ApplicationContext.xml.
NOT in the view.xml !!! It would not be found.
注意:
把JsonExceptionResolver 注册在ApplicationContext.xml,
而不是view.xml !!!,不然会找不到它。
JsonErrorHandlers
Json错误处理器
JsonErrorHandlers signals the client that something went wrong. For further informations see Errorhandling
JsonErrorHandlers 发响应到客户端因为有些产生了错误。详细信息参见Errorhandling
HttpStatusError
Sets a new Response-Status by response.setStatus(errorCode).
用response.setStatus(错误编码)设置一个Response-Status。
ModelFlagError
Adds a simple key-value-pair to the model.
在Model中添加一个简单键值对。
JsonExceptionHandler
Json异常处理器
JsonExceptionHandler convert the java.lang.Exception object to be added to to the json-string .
JsonExceptionHandler负责把Java异常对象转换成一个Json字符串。
ExceptionMessageExceptionHandler
Adds the java.lang.Exception Message to the model.The default modelKey is "exception.message ". The ExceptionMessageExceptionHandler adds the ErrorMessage in the "Exception Classname : Exception Message " format.Example : "java.lang.IllegalArgumentException : Please set Parameter "
添加一个Java异常到Model里。默认的ModelKey是"exception.message ". ExceptionMessageExceptionHandler 用"Exception Classname : Exception Message "格式设置错误信息。
比如 : "java.lang.IllegalArgumentException : Please set Parameter "
StackTraceExceptionHandler
Adds the whole Exception StackTrace to the model. The default modelKey is "exception.stacktrace ". You can replace the linebreak "\n" with an html-linebreake </br> by setting the replaceLineBreakes property true.The default value is replaceLineBreakes=false.
把完整的堆栈异常添加到Model.默认的ModelKey是"exception.stacktrace".当replaceLineBreakes=true时表示可用Html</br>标记代替"\n",默认replaceLineBreakes=false。
<beans>
<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="exceptionMessageExceptionHandler" />
<ref bean="stackTraceExceptionHandler" />
</list>
</property>
</bean>
<bean name="exceptionMessageExceptionHandler"
class="org.springframework.web.servlet.view.json.exception.ExceptionMessageExceptionHandler" />
<bean name="stackTraceExceptionHandler"
class="org.springframework.web.servlet.view.json.exception.StackTraceExceptionHandler" />
<bean name="statusError"
class="org.springframework.web.servlet.view.json.error.HttpStatusError"/>
<bean name="modelFlagError"
class="org.springframework.web.servlet.view.json.error.ModelFlagError"/>
</beans>
Result:
=======
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.[...]
[...]"
}
2. ExceptionMessageExceptionHandler
You can customize the model-key of the ExceptionMessage. Default is exception.message
你也可以自己订制Model-key方式的异常信息。默认是exception.message
<beans>
<bean id="exceptionResolver"
class="org.springframework.web.servlet.view.json.exception.JsonExceptionResolver">
<property name="exceptionView"><value>jsonView</value></property>
<property name="exceptionHandler">
<list>
<ref bean="exceptionMessageExceptionHandler" />
</list>
</property>
</bean>
<bean name="exceptionMessageExceptionHandler"
class="org.springframework.web.servlet.view.json.exception.ExceptionMessageExceptionHandler">
<property name="modelKey"><value>myKey</value></property>
</bean>
</beans>
Result:
=======
Response-Status : 200
{
"myKey":"java.lang.Exception: You throw an exeption !"
}
3. StackTraceExceptionHandler
You can customize the model-key of the Exception-StackTrace (Default is exception.stacktrace ); You also can prepare the StackTrace for an html-view by replacing the linebreak "\n" with an html-linebreake </br>. The default value is replaceLineBreakes=false.
你能订制Model-Key的堆栈跟踪异常(默认是exception.stacktrace);你也能用Html视图模式展现它,replaceLineBreakes=true可用Html</br>标记代替"\n",默认replaceLineBreakes=false
<beans>
<bean id="exceptionResolver"
class="org.springframework.web.servlet.view.json.exception.JsonExceptionResolver">
<property name="exceptionView"><value>jsonView</value></property>
<property name="exceptionHandler">
<list>
<ref bean="stackTraceExceptionHandler" />
</list>
</property>
</bean>
<bean name="stackTraceExceptionHandler"
class="org.springframework.web.servlet.view.json.exception.StackTraceExceptionHandler">
<property name="replaceLineBreakes"><value>true</value></property>
<property name="modelKey"><value>myKey</value></property>
</bean>
</beans>
Result:
=======
Response-Status : 200
{
"myKey": "java.lang.Exception: You throw an exeption !
<\br>\tat org.thing.spring.json.controller.[...]
<\br>\tat org.springframework.web.servlet.mvc.[...]
[...]"
}
4. Custom implementation of JsonExceptionHandler
It is possible to realize some totally different behaviours by implementing the JsonExceptionHandler interface.
你也可以自己实现JsonExceptionHandler用一些完全不同的方式重构它。
public class MyExceptionHandler implements JsonExceptionHandler {
public void triggerException(Exception exception, Map model,
HttpServletRequest request, HttpServletResponse response)
throws Exception{
// Do something ...
}
}
Other Configurations
其它配置
Convert all model values. 转换Model所有的值
ContentType 内容类型
Encoding 字符编码
1. Convert all model values.
你可以像下面展现的那样在DefaultJsonStringWriter中设置convertAllMapValues=true,可动态的转换非CommandBean类型,详细信息参考:
绑定 -4.转换所有Model的值
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
<property name="jasonWriter"><ref bean="jasonWriter"/></property>
</bean>
<bean name="jasonWriter"
class="org.springframework.web.servlet.view.json.converter.DefaultJsonStringWriter">
<property name="convertAllMapValues"><value>true</value></property>
</bean>
</beans>
2. Content type
To change the response content type of the JsonView you can set the content type property like below.
你可以像下面展现的那样,在JsonView设置contentType的值来改变输出内容的文本类型。
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
<property name="contentType"><value>application/json</value></property>
</bean>
</beans>
3. Encoding
To change the response encoding of the JsonView you can set the encoding property like below.
你可以像下面展现的那样,在JsonView设置encoding的值来改变输出内容的字符编码。
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
<property name="encoding"><value>ISO-8859-1</value></property>
</bean>
</beans>
Demo-Application
演示程序
About
关于
The DemoApplication shows the json-result strings of the following usecases:
这个演示程序显示了下列用例生成的Json-Result方式的结果集
GET-Request with Controller-Interface
[see Quickstart] 用Controller-Interface方式提交Get请求
Post-Request with Command-Controller
[see Quickstart] 用Command-Controller方式提交Post请求
GET/Post-Request with SimpleForm-Controller
[see Quickstart] 用SimpleForm-Controller方式提交GET/Post请求
Request with thrown Exception caught by the JsonExceptionResolver
[see Quickstart] 使用JsonExceptionResolver抛出异常捕获信息的请求
Install
安装
Just download the war file
HERE and deploy it to your application server.
It is tested for apache-tomcat-5.5.25.
仅仅需要
在这里下载war并部署到你的应用服务器.这里的测试环境建立在apache-tomcat-5.5.25.
Quickstart
快速开始
Start setting up a Spring-MVC application base first.
首先了解Spring-MVC的基础.
Further Information:
详细信息参考如下资料:
The easiest way to configurate the Spring Json-View as a bean is to register a XmlViewResolver.
配置Spring Json-View非常容易,只需要注册一个XML视图解析器
Spring ApplicationContext
<beans>
[...]
<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"/>
</beans>
Quickstart - GET-Request with Controller-Interface
快速开始-用Controller-Interface提交Get请求
With the Controller-Interface validating or binding is not supported by spring. It is easy to use it for GET-Requests.
The json-view response is just the json-string of the Model-Map created in the Controller . No errors are included or values formated.
在Spring中不支持Controller-Interface的验证或绑定。它能容易地处理来自Get方式的请求。
它在Controller中仅仅返回一个用Model-Map产生的Json字符串,没有错误包含或者格式转换。
Spring ApplicationContext
<beans>
<bean name="simpleJsonGetController"
class="org.thing.spring.json.controller.SimpleJsonGetController"/>
<bean name="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.json">simpleJsonGetController</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"/>
</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 Get (ControlerInterface)</h2>
<b>firstname : </b><span id="firstname"></span><br/>
<b>secondname : </b><span id="secondname"></span><br/>
</br>
<button id="getName">get name</button>
<button id="clearName">clear name</button><br/>
</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#getName' : function(element){
element.onclick = function(){
new Ajax.Request('hello.json', { method:'get',
onSuccess: function(transport, json){
var json = transport.responseText.evalJSON();
printResult(transport);
$('firstname').innerHTML = json.firstname;
$('secondname').innerHTML = json.secondname;
}
});
}
},
'button#clearName' : function(element){
element.onclick = function(){
$('firstname').innerHTML = '';
$('secondname').innerHTML = '';
}
}
};
Behaviour.register(myrules);
Controller Source
public class SimpleJsonGetController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Map model = new HashMap();
model.put("firstname", "Peter");
model.put("secondname", "Schmitt");
return new ModelAndView("jsonView", model);
}
}
Result
Status : 200
Result:
{"firstname":"Peter","secondname":"Schmitt"}
Quickstart - POST request with Command-Controller
快速开始- 用Command-Controller提交Post请求
The Command-Controller serves you a filled CommandBean. Validating or binding is supported by Spring. But you have to handle binding and validating results in your Controller Class. It is easy to use for simple POST requests.The json-view response is just the json-String of the Model-Map created in the Controller . No errors are included or values formated.
Command-Controller提供一个完整的CommandBean,Spring对它提供校验和绑定支持。但是你不得不在你的控制器类里添加校验和绑定处理。它处理简单的Post请求非常容易。它在Command-Controller中仅仅返回一个用Model-Map产生的Json字符串,没有错误包含或者格式转换。
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>
</bean>
<bean name="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.json">simpleJsonPostCommandController</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"/>
</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/>
<button id="clearData">clear name</button>
<button id="cc_postData">send data to CommandController</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#clearData' : function(element){
element.onclick = function(){
$('t_placeofbirth').innerHTML = '';
$('t_birthday').innerHTML = '';
$('error').innerHTML = '';
},
'button#cc_postData' : function(element){
element.onclick = function(){
new Ajax.Request('hello.json', {
method:'post',
parameters: $('form').serialize(false),
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
printResult(transport);
$('t_placeofbirth').innerHTML = json.placeofbirth;
$('t_birthday').innerHTML = json.birthday;
$('error').innerHTML = '';
},
onFailure: function(transport){
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 SimpleJsonPostCommandController extends AbstractCommandController {
@Override
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 ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object command,
BindException exception) throws Exception {
SpringJsonForm bean = (SpringJsonForm) command;
ModelAndView modelAndView = new ModelAndView("jsonView");
modelAndView.addObject("birthday", bean.getBirthday());
modelAndView.addObject("placeofbirth", bean.getPlaceofbirth());
return modelAndView;
}
}
Result
Status : 200
Result:
{"placeofbirth":"Sydney","birthday":"Wed Jan 30 00:00:00 GMT 2008"}
Quickstart - GET/POST request with SimpleForm-Controller
快速开始-用SimpleForm-Controller提交GET/POST请求
The Command-Controller serves you 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
Command-Controller提供一个完整的CommandBean,Spring对它提供校验和绑定支持。它在Command-Controller中返回一个用Model-Map产生的Json字符串,返回信息中包含字段错误、全局错误和绑定。支持CommandBean属性类型转换。Get请求需要依赖formBackingObject方法Post请求需要依赖onSubmitAction方法详细信息参见文档
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:
{"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!"
}}
Quickstart - Request with thrown Exception (JsonExceptionResolver)
快速开始-使用JsonExceptionResolver抛出异常捕获信息的请求
The exceptionhandling is realized by an implemention of an HandlerExceptionResolver: The JsonExceptionResolver. You have to register at least one JsonErrorHandlers or JsonExceptionHandler to manipulate the response in the case of an thrown exception.JsonErrorHandlers signals the client that something went wrong. For further informations see Errorhandling JsonExceptionHandler convert the java.lang.Exception object to be added to to the json-string.For further information see the Exceptionhandling
实现异常处理是通过异常分析处理分析器来完成:JsonExceptionResolver。你仅仅需要注册一个JsonErrorHandlers或者JsonExceptionHandler操作一个返回信息以便抛出异常。 JsonErrorHandlers 发响应到客户端因为有些产生了错误。详细信息参见ErrorhandlingJsonExceptionHandler 转换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.[...]
[...]"
}
Download
下载
You can download Spring Json View
你能下载Spring Json View的:
Project sources 工程源码
Binary jar Jar包
Demo-Application 演示程序
SVN
SVN地址
FAQ
问答
Does spring json-view provides all the features we know from spring-mvc?
Does spring json-view streams the json result?
Which json engine do you use?
Why didn't you use json-lib?
Does spring json-view provides all the features we know from spring-mvc?
Yes, except one little thing. Spring Json View can only bind explicit properties of a collection of beans (see binding documentation)
Spring Json-view提供所有的我们知道的Spring-MVC特征吗?
是的,几乎支持所有。Spring Json View能唯一绑定ConllectionBean的详细属性(参见文档Binding部分)
Does spring json-view streams the json result?
No, not yet. For now it generates a string and writes it to the OutputStream.
Spring Json-view 直接输出到Json结果集吗?
不,还没有。暂时它是先产生一个字符串再写到输出流里。
Which json engine do you use?
sojo.
Spring Json View使用哪一个Json引擎
Why didn't you use json-lib?
Until now I haven't found a way to convert the property values by the CommensBeanUtils-Syntax.
为什么不使用Json-Lib呢?
因为迄今为止我还没有发现一种方法能转换符合CommonsBeanUtils语法的属性值。