@InitBinder注解的使用
原创
©著作权归作者所有:来自51CTO博客作者Dongguabai的原创作品,请联系作者获取转载授权,否则将追究法律责任
用法一:绑定同属性多对象
比如这里有一个User类:
Person类:
两个类都有name和address属性。
在Controller中:
在浏览器中访问:
发现name和address同时被绑定到了user和person中,但是如果只想绑定到指定的类中,可以这么做:
@InitBinder里面的参数表示参数的名称。
再来测试:
这个WebDataBinder还有一个setDisallowedFields()方法,可以让某个属性无法被接收。比如:
再测试:
用法二:类型转换
比如现在将前端传递来的时间字符串转化为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();
}
}
}
测试: