当前位置: 移动技术网 > IT编程>开发语言>Java > spring mvc绑定参数之类型转换有三种方式:

spring mvc绑定参数之类型转换有三种方式:

2020年07月17日  | 移动技术网IT编程  | 我要评论

spring mvc绑定参数之类型转换有三种方式:

1.实体类中加日期格式化注解

@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm”)
private Date creationTime;

2.属性编辑器

spring3.1之前

在Controller类中通过@InitBinder完成

/**
* 在controller层中加入一段数据绑定代码
* @param webDataBinder
*/
@InitBinder
public void initBinder(WebDataBinder webDataBinder) throws Exception{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd hh:mm”);
simpleDateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
}
备注:自定义类型转换器必须实现PropertyEditor接口或者继承PropertyEditorSupport类
写一个类 extends propertyEditorSupport(implements PropertyEditor){
public void setAsText(String text){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy -MM-dd hh:mm”);
Date date = simpleDateFormat.parse(text);
this.setValue(date);
}
public String getAsTest(){
Date date = (Date)this.getValue();
return this.dateFormat.format(date);
}
}

3. 类型转换器Converter

全局类型转换

/**

  • 把字符串转换成日期的转换器
  • @author rt
    /
    public class StringToDateConverter implements Converter<String, Date>{
    /
    *
  • 进行类型转换的方法
    */
    public Date convert(String source) {
    // 判断
    if(source == null) {
    throw new RuntimeException(“参数不能为空”);
    }
    try {
    DateFormat df = new SimpleDateFormat(“yyyy-MM-dd”);
    // 解析字符串
    Date date = df.parse(source);
    return date;
    } catch (Exception e) {
    throw new RuntimeException(“类型转换错误”);
    }
    }
    }
  1. 注册自定义类型转换器,在springmvc.xml配置文件中编写配置
    在这里插入图片描述

本文地址:https://blog.csdn.net/weixin_42478365/article/details/107368939

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网