在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。
解决的办法就是使用spring mvc提供的@InitBinder标签
@Controller
public class BoceController extends BaseController {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class,new StrToInteger());
}
}
package com.cloud.api.util;
import java.beans.PropertyEditorSupport;
public class StrToInteger extends PropertyEditorSupport{
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
//text 中获取请求对象
//2. 将请求对象转化为 需要的对象
Integer value = Integer.parseInt(text);
//3 将转化的对象放入 setValue 方法中
setValue(value);
}
@Override
public String getAsText() {
System.out.println("=++++++++++++++++++++++++++++++++");
return getValue().toString();
}
}
StrToInteger 这个类是在接收到post 提交的字段后,然后 把接收到的string 字符串,转化为 Integer 对象的方法。