spring mvc绑定对象String转Date

使用spring的mvc,直接将页面参数绑定到对象中,对象中有属性为Date时会报错,此时需要处理下。

同样的,其他的需要处理的类型也可以用这种方法。

在controller中加入代码

  1. @InitBinder
  2. protected void initBinder(HttpServletRequest request,
  3. ServletRequestDataBinder binder) throws Exception {
  4. //对于需要转换为Date类型的属性,使用DateEditor进行处理
  5. binder.registerCustomEditor(Date.class, new DateEditor());
  6. }
@InitBinder
protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
    //对于需要转换为Date类型的属性,使用DateEditor进行处理
    binder.registerCustomEditor(Date.class, new DateEditor());
}

DateEditor为自定义的处理类,继承自PropertyEditorSupport,处理方法为public void setAsText(String text) throws IllegalArgumentException

  1. import org.springframework.util.StringUtils;
  2. import java.beans.PropertyEditorSupport;
  3. import java.text.DateFormat;
  4. import java.text.ParseException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. public class DateEditor extends PropertyEditorSupport {
  8. private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
  9. private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  10. private DateFormat dateFormat;
  11. private boolean allowEmpty = true;
  12. public DateEditor() {
  13. }
  14. public DateEditor(DateFormat dateFormat) {
  15. this.dateFormat = dateFormat;
  16. }
  17. public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
  18. this.dateFormat = dateFormat;
  19. this.allowEmpty = allowEmpty;
  20. }
  21. /**
  22. * Parse the Date from the given text, using the specified DateFormat.
  23. */
  24. @Override
  25. public void setAsText(String text) throws IllegalArgumentException {
  26. if (this.allowEmpty && !StringUtils.hasText(text)) {
  27. // Treat empty String as null value.
  28. setValue(null);
  29. } else {
  30. try {
  31. if(this.dateFormat != null)
  32. setValue(this.dateFormat.parse(text));
  33. else {
  34. if(text.contains(":"))
  35. setValue(TIMEFORMAT.parse(text));
  36. else
  37. setValue(DATEFORMAT.parse(text));
  38. }
  39. } catch (ParseException ex) {
  40. throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
  41. }
  42. }
  43. }
  44. /**
  45. * Format the Date as String, using the specified DateFormat.
  46. */
  47. @Override
  48. public String getAsText() {
  49. Date value = (Date) getValue();
  50. DateFormat dateFormat = this.dateFormat;
  51. if(dateFormat == null)
  52. dateFormat = TIMEFORMAT;
  53. return (value != null ? dateFormat.format(value) : "");
  54. }
  55. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值