计算机考试模拟网站怎么做,哪些网站做推广比较好,自助建站源码php,网站建设昆山前些天发现了一个巨牛的人工智能学习网站#xff0c;通俗易懂#xff0c;风趣幽默#xff0c;忍不住分享一下给大家。点击跳转到教程。
使用 SpringMVC 时#xff0c;常遇到表单中日期字符串和 JavaBean 的 Date 类型的转换#xff0c;而 SpringMVC 默认不支持这个格式的…前些天发现了一个巨牛的人工智能学习网站通俗易懂风趣幽默忍不住分享一下给大家。点击跳转到教程。
使用 SpringMVC 时常遇到表单中日期字符串和 JavaBean 的 Date 类型的转换而 SpringMVC 默认不支持这个格式的转换故需要手动配置自定义数据的绑定才能解决这个问题。 在需要日期转换的 Controller 中使用 SpringMVC 的注解 initbinder 和 Spring 自带的 WebDateBinder 类来操作。 WebDataBinder 是用来绑定请求参数到指定的属性编辑器.由于前端传到 controller 里的值是 String 类型的当往 Model 里 Set这个值的时候如果 set 的这个属性是个对象Spring 就会去找到对应的 editor 进行转换然后再 SET 进去。 代码如下
InitBinder
public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat new SimpleDateFormat(yyyy-MM-dd); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
需要在SpringMVC的配置文件加上
!-- 解析器注册 --
bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter property namemessageConverters list ref beanstringHttpMessageConverter/ /list /property
/bean
!-- String类型解析器允许直接返回String类型的消息 --
bean idstringHttpMessageConverter classorg.springframework.http.converter.StringHttpMessageConverter/
换种写法
mvc:annotation-drivenmvc:message-convertersbean classorg.springframework.http.converter.StringHttpMessageConverterconstructor-arg valueUTF-8//bean/mvc:message-converters
/mvc:annotation-driven
拓展 spring mvc在绑定表单之前都会先注册这些编辑器Spring自己提供了大量的实现类诸如CustomDateEditor CustomBooleanEditorCustomNumberEditor等许多基本上够用。 使用时候调用WebDataBinder的registerCustomEditor方法registerCustomEditor源码
public void registerCustomEditor(Class? requiredType, PropertyEditor propertyEditor) {getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
}
第一个参数 requiredType 是需要转化的类型。 第二个参数 PropertyEditor 是属性编辑器它是个接口以上提到的如 CustomDateEditor 等都是继承了实现了这个接口的PropertyEditorSupport 类。 我们也可以不使用他们自带的这些编辑器类。 我们可以自己构造
import org.springframework.beans.propertyeditors.PropertiesEditor;public class DoubleEditor extends PropertyEditorSupport {Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text null || text.equals()) {text 0;}setValue(Double.parseDouble(text));}Overridepublic String getAsText() {return getValue().toString();}
} 转自https://www.cnblogs.com/soundcode/p/6519036.html 另一举例文章见 SpringMvc 注解 InitBinder 表单多对象精准绑定接收