介绍
@InitBinder用于在@Controller中标注于方法,表示为当前控制器注册一个属性编辑器或者其他,只对当前的Controller有效。 @InitBinder必须有一个参数WebDataBinder
WebBindingInitializer
WebBindingInitializer:实现WebBindingInitializer,重写initBinder注册的属性编辑器是全局的属性编辑器,对所有的Controller都有效。
@InitBinder例子介绍
日期格式化
@Controller
public class GlobalController {
@RequestMapping("test/{date}")
public void test(@PathVariable Date date, HttpServletResponse response) throws IOException
response.getWriter().write( date);
}
@InitBinder//必须有一个参数WebDataBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
}
WebBindingInitializer 例子
public class MyWebBindingInitializer implements WebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
// TODO Auto-generated method stub
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
在springMVC的配置文件里面定义一个AnnotationMethodHandlerAdapter,并设置其WebBindingInitializer属性为我们自己定义的WebBindingInitializer对象
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0"/>
<property name="webBindingInitializer">
<bean class="com.xxx.blog.util.MyWebBindingInitializer"/>
</property>
</bean>