spring自动类型转换========Converter和PropertyEditor

Spring有两种自动类型转换器,一种是Converter,一种是propertyEditor。

两者的区别:Converter是类型转换成类型,Editor:从string类型转换为其他类型。

从某种程度上,Converter包含Editor。如果出现需要从string转换到其他类型。首选Editor。

Converter代码展示:

实现string类型转换Date。

MyConverter类

public class MyConverter implements Converter<String, Date> {

    public Date convert(String source) {
        System.out.println("进入了 converter");
        //创建类型转换器
        @SuppressWarnings("unused")
        SimpleDateFormat simpleDateFormat = getSimpleDateFormat(source);
        Date date = null;
        try {
            date = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    private SimpleDateFormat getSimpleDateFormat(String source) {
        SimpleDateFormat simpleDateFormat;
        if (Pattern.matches("^\d{4}-\d{2}-\d{2}$", source)) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\d{4}/\d{2}/\d{2}$", source)) {
            simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        } else if (Pattern.matches("^\d{4}\d{2}\d{2}$", source)) {
            simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        } else {
            throw new TypeMismatchException("", Date.class);
        }

        return simpleDateFormat;
    }

}

Controller类

@Controller
@RequestMapping("/student")
public class StudentController {
    @RequestMapping("/add")
    public ModelAndView add(Student student) {
        System.out.println(student.getName());
        System.out.println(student.getBirthday());
        return new ModelAndView("success");

    }

    @ExceptionHandler
    public ModelAndView exceptionMethod(Exception ex, ModelAndView mv, HttpServletRequest request) {
        System.out.println("进入新增界面");
        //获取前台输入的信息
        String name = request.getParameter("name");
        String birthday = request.getParameter("birthday");
        String message = ex.getMessage();
        if (message.contains(name)) {
            mv.addObject("nameerro", "用户名输入有误");

        }
        if (message.contains(birthday)) {
            mv.addObject("birthdayerro", "日期输入有误");
        }
        mv.addObject("name", name).addObject("birthday", birthday).setViewName("index");
        return mv;
    }

}

纠结了一下,还是决定写一下Editor的代码,然后打一局魂斗罗,希望多年后的自己还可以这么喜欢这款游戏。

尴尬了,原来还可以加行号。。。

 1 @Controller
 2 @RequestMapping("/student")
 3 public class StudentController {
 4     @RequestMapping("/add")
 5     public ModelAndView add(Student student) {
 6         System.out.println(student.getName());
 7         System.out.println(student.getBirthday());
 8         return new ModelAndView("success");
 9 
10     }
11 
12     /**
13      * binder.registerCustomEditor初始化参数的绑定 newcustomDateEditor:创建类型编辑器 true
14      * 允许日期格式为空
15      * 
16      */
17     @InitBinder
18     public void initBinder(WebDataBinder binder) {
19         binder.registerCustomEditor(Date.class, new MyEditor());
20     }
21 }
public class MyEditor extends PropertiesEditor {
    @Override
    public void setAsText(String source) throws IllegalArgumentException {
        SimpleDateFormat sdf = getDate(source);
        Date parse = null;
        // 类型转化
        try {
            parse = sdf.parse(source);
            setValue(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param source
     *            传递来的日期格式的字符串
     * 
     */
    private SimpleDateFormat getDate(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat();
        // 判断
        if (Pattern.matches("^\d{4}-\d{2}-\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\d{4}/\d{2}/\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyy/MM/dd");
        } else if (Pattern.matches("^\d{4}\d{2}\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyyMMdd");
        } else {
            /**
             * 都不匹配了 就让它抛出 TypeMismatchException异常 public
             * TypeMismatchException(Object value, Class<?> requiredType) {
             * vallue 值能对应requiredType 类型 就不会出现异常 我们就得写一个不能转换的
             */
            throw new TypeMismatchException("", Date.class);
        }
        return sdf;
    }
}

自我感觉:Editor代码量比Controller少,但还是都记不住。。。

我去魂斗罗了哈哈哈。。。

仔细看了一下,纠正一下,并不是Controller代码量多,在页面设置了回显,所以代码多了。但是还是不太明白,return、date date=null,date parse=null。下午讨论以后,在写感受。

原文地址:https://www.cnblogs.com/Hei-po/p/6812213.html