javaee springMVC自定义转换类实现日期类型转换

定义转换类

java 复制代码
package com.test.editor;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//自定义转换类
public class DateEditor extends PropertyEditorSupport {

    //将提交过来的字符串 转换为 日期类型
    //比如 2020-01-01
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        //super.setAsText(text);
        //定义简单日期转换对象
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");

        //将字符串转换为日期类型
        Date date=null;

        try {
            date= simpleDateFormat.parse(text);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //将转换好的数据赋值给对应的属性
        setValue(date);

    }
}

加载转换类

java 复制代码
package com.test.controller;

import com.test.editor.DateEditor;
import com.test.pojo.Users2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

@Controller
@RequestMapping("/users2")
public class Users2Controller {

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        //将自定义的转换类注册到binder对象中
        binder.registerCustomEditor(Date.class,new DateEditor());

    }


    @RequestMapping("/addUser")
    public String addUser(Users2 user2)
    {
         System.out.println(user2);

         return "success";
    }
}
相关推荐
小bo波7 小时前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯8 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
apocelipes10 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户83562907805112 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent17 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
SamDeepThinking19 小时前
裁掉那个差程序员后,给你看团队里高手的代码:这个习惯,希望你有
java·后端·程序员
朕瞧着你甚好20 小时前
技术雷达 & Java 集成评估报告 — Apache Tika 3.3.1
java·ai编程
咕白m62520 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
MacroZheng20 小时前
短短几天,暴涨2.8万Star!又一款编程神器开源!
java·人工智能·后端
SamDeepThinking21 小时前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试