@InitBinder
1 SpringMvc @InitBinder 表单多对象精准绑定接收
https://blog.youkuaiyun.com/xsf1840/article/details/73556633 说的很好
提交连个对象的处理
<form action="/test/test" method="post">
<input type="text" name="user.id" value="huo_user_id">
<input type="text" name="user.name" value="huo_user_name">
<input type="text" name="addr.id" value="huo_addr_id">
<input type="text" name="addr.name" value="huo_addr_name">
<input type="submit" value="提交">
</form>
@Controller
@RequestMapping("/test")
public class TestController {
// 绑定变量名字和属性,参数封装进类
@InitBinder("user")
public void initBinderUser(WebDataBinder binder) {
binder.setFieldDefaultPrefix("user.");
}
// 绑定变量名字和属性,参数封装进类
@InitBinder("addr")
public void initBinderAddr(WebDataBinder binder) {
binder.setFieldDefaultPrefix("addr.");
}
@RequestMapping("/test")
@ResponseBody
public Map<String,Object> test(HttpServletRequest request,@ModelAttribute("user") User user,@ModelAttribute("addr") Addr addr){
Map<String,Object> map=new HashMap<String,Object>();
map.put("user", user);
map.put("addr", addr);
return map;
}
2 时间类型的转换
在使用SpringMVC的时候,经常会遇到表单中的日期字符串和JavaBean的Date类型的转换,而SpringMVC默认不支持这个格式的转换,所以需要手动配置,自定义数据的绑定才能解决这个问题。
Controller继承的BaseController中
/**
* 初始化绑定<br/>
* @param request http请求实例
* @param binder 绑定实例
* @throws Exception
* */
@InitBinder
public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new DateEditor());
}
/**
* <p><strong>类名: </strong></p>DateEditor <br/>
* <p><strong>功能说明: </strong></p>日期数据自动转换类. <br/>
* @since JDK 1.8
*/
public class DateEditor extends PropertyEditorSupport {
public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void setAsText(String text)
{
setValue(parseString(text));
}
private Object parseString(String text)
{
Date date = null;
if (null != text && !"".equals(text)) {
try {
dateTimeFormat.setLenient(false);
date = dateTimeFormat.parse(text);
} catch (ParseException e) {
//e.printStackTrace();
}
if (date == null) {
try {
dateFormat.setLenient(false);
date = dateFormat.parse(text);
} catch (ParseException e) {
//e.printStackTrace();
}
}
}
return date;
}
}
3 是否绑定某个属性 或者只绑定某个属性
@InitBinder
private void initBinder(WebDataBinder binder){
//由表单到JavaBean赋值过程中哪一个值不进行赋值
binder.setDisallowedFields("lastName");
}