我有一个命令对象,它代表提交的表单对象。如果表单输入字段中的值为空,我希望它在命令对象中为 null
。
我读到了不同的SO question显示使用 InitBinder
我尝试过,但 initBinder
方法从未被调用。
我的 Controller
package com.example;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.example.MyDTO;
@Controller
public class MyControllerImpl implements MyController {
@InitBinder("myControllerImpl")
public void initBinder(WebDataBinder binder) {
System.out.println("init binder");
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
@Override
public String someAction( MyDTO someDTO ) {
System.out.println(someDTO);
// Do something with DTO. I want blank values to be null here
return "somePage;
}
}
DTO
package com.example;
public class MyDTO {
private String name;
public String getName() {
return name;
}
public String setName() {
return name;
}
}
我还尝试将类名添加到 InitBinder
注释中
@InitBinder("myControllerImpl")
但是没有成功。
为了调用 init 绑定(bind)程序,我缺少什么?
我正在使用 Java 6 和 Spring 3
最佳答案
您需要将@ControllerAdvice
添加到 Controller 类。
关于java - 将 InitBinder 与命令对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297719/