用法一:绑定同属性多对象

比如这里有一个User类:

@InitBinder注解的使用_java

Person类:

@InitBinder注解的使用_java_02

两个类都有name和address属性。

在Controller中:

@InitBinder注解的使用_ide_03

在浏览器中访问:

@InitBinder注解的使用_ide_04

发现name和address同时被绑定到了user和person中,但是如果只想绑定到指定的类中,可以这么做:

@InitBinder注解的使用_ide_05

@InitBinder里面的参数表示参数的名称。

再来测试:

@InitBinder注解的使用_java_06

这个WebDataBinder还有一个setDisallowedFields()方法,可以让某个属性无法被接收。比如:

@InitBinder注解的使用_ide_07

再测试:

@InitBinder注解的使用_java_08

用法二:类型转换

比如现在将前端传递来的时间字符串转化为Date类型。一般可以使用一个BaseController让其他Controller继承使用。

Controller代码:

package com.example.demoClient.controller;

import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @author Dongguabai
* @date 2018/11/2 14:32
*/
@RestController
public class TestController {

@RequestMapping("/test1")
public Object test(Date date){
return date.toLocaleString();
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new MyDateEditor());
binder.registerCustomEditor(Double.class, new DoubleEditor());
binder.registerCustomEditor(Integer.class, new IntegerEditor());
}

private class MyDateEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(text);
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(text);
} catch (ParseException e1) {
}
}
setValue(date);
}
}

public class DoubleEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
setValue(Double.parseDouble(text));
}

@Override
public String getAsText() {
return getValue().toString();
}
}

public class IntegerEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
setValue(Integer.parseInt(text));
}

@Override
public String getAsText() {
return getValue().toString();
}
}


}

测试:

@InitBinder注解的使用_java_09