发表时间:2008-12-11
最后修改:2009-05-25
校验
来自Post的请求校验的非常容易。仅仅需要按Spring方式注册一个校验器。Spring Json View 在返回Json字符串数据时增加字段错误处理
校验器
用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
在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>
效果
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!"
}}