通过注解实现spring属性编辑器

在struts2里面有个叫类型转换器的东东,而在spring里面也有个类似的功能,叫属性编辑器

通过注解实现spring属性编辑器


以前用xml配置实现过spring的竖向编辑器,今天突然想到能不能用注解来实现spring的属性编辑器配置


比如网站客户端需要传入一个时间数据,我们需要对这个时间进行处理,因为后台只能获得string类型的数据,就是说你的控制器方法里面的参数,只有string。对于date类型是无法获取到的

一共需要三步

第一:创建有一个继承了PropertyEditorSupport类的类,然后重新setAsText方法


public class customerProperty extends PropertyEditorSupport{
	private String format = "yyyy-MM-dd";

	public String getFormat() {
		return format;
	}
	public void setFormat(String format) {
		this.format = format;
	}
	
	public void setAsText(String text) throws IllegalArgumentException{
		SimpleDateFormat sf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sf.parse(text);
			this.setValue(date);
			//this.setValue(sf.parse(text));
		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
第二步:在控制器(Controller)里面添加以下方法


使用注解@InitBinder注解


@InitBinder(value = "birthday")
public void initBinder(WebDataBinder binder){
	binder.registerCustomEditor(Date.class, new customerProperty());
}


这个注解会在调用Controller之前被使用


第三步:在控制器(Controller)里面,写一个@RequestMapping测试


@InitBinder(value = "birthday")
public void initBinder(WebDataBinder binder){
	binder.registerCustomEditor(Date.class, new customerProperty());
}

//用户注册
@RequestMapping("/register")
public String userregister(Date birthday, String username, String password,
		HttpSession session, HttpServletRequest request) {
	System.out.println(birthday.getTime());
		
	return "member/login";
}


我这里主要说说用InitBinder注解的一些注意事项

a、里面的value参数必须要和我们的RequestMapping方法里面的参数一致

b、value里面的参数可以是多个,当是很多个参数的时候,必须有一个是和我们需要转换的参数是一致的,如您可以这样写


@InitBinder(value = {"birthday","birthday1"})
public void initBinder(WebDataBinder binder){
	binder.registerCustomEditor(Date.class, new customerProperty());
}
如果您需要转换的参数是birthday或birthday1都是可以的


c、通过InitBinder注解的方法,其方法名不是唯一的,就是说您可以在一个控制器内注册很多个属性编辑器,如以下代码是合法的


@InitBinder(value = {"birthday","birthday1"})
public void initBinder(WebDataBinder binder){
	binder.registerCustomEditor(Date.class, new customerProperty());
}

@InitBinder(value = {"aa1","aa2"})
public void aaaa(WebDataBinder binder){
	binder.registerCustomEditor(aaaa.class, new aaaa());
}
d、您大致可以猜到这局代码里面参数的含义


binder.registerCustomEditor(Date.class, new customerProperty());

第一个参数表示转换的类型

第二个参数表示具体的属性编辑器





爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img