springMVC @initBinder 使用


controller代码:

@Controller
public class WelcomeController {
	
	@InitBinder
	public void iniiBinder(WebDataBinder binder){
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		format.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
	}
	
	
	@RequestMapping("/welcome")
	public void welcome(HttpServletResponse response ,Date date) throws IOException{
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		response.getWriter().write("welcome here again !  current date is "+format.format(date));
	}

}


url : http://localhost:8080/mymvc/welcome?date=2015-11-10

浏览器输出:welcome here again ! current date is 2015-11-10


备注:

initBinder 注解方法首先执行,然后执行requestMapping注解方法,字符串参数自动转成了指定的日期。如果是spring 的版本大于等于4.2 则 @initBinder 方法也可以写作

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }

有一个问题是initBinder 只对当前controller起左右,其它controller无效,如何让initBinder 对所有controller有效呢?我还没有研究出来哈。


-------------------- 华丽的分割线 -------------------------------------------------------

关于@initBinder 对所有 controller 都有效有了解决方案。

利用 @ControllerAdvice注解 。在有此注解的类里 写 @initBinder 方法,并指明目标 类,则可对目标类起作用。

有三种 方式制定目标类:

// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class AnnotationAdvice {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class BasePackageAdvice {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class AssignableTypesAdvice {}


我选的第二种,目标锁定到指定的包下所有的类。

代码如下


@ControllerAdvice("com.lls.mvc")
public class BasePackageAdvice {

	@InitBinder
	public void iniiBinder(WebDataBinder binder){
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		format.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
	}
	
注意 在配置文件中将该类扫描

<context:component-scan base-package="com.lls.config" />

这样 就可以将其它的controller的关于日期的initBinder注解方法去掉了。

每次请求都会先调用 @ControllerAdvice 类下的 @initBinder 方法。然后再调用 controller的 @requestMapping 对应的方法。



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值