initBinder转换日期格式

@Controller
public class FirstController {
    @RequestMapping("/first")
    //类型转化工作一定是在真正的handler方法执行前执行的
    public String doFirst(Date birthday ,int age)throws Exception{
        System.out.println(birthday+"=================");
        System.out.println(age+"=============");
        return "/WELCOME.jsp";
    }

    @ExceptionHandler(TypeMismatchException.class)
    public ModelAndView parseException(TypeMismatchException ex, HttpServletRequest request){
        System.out.println("hehehehe哈");
        ModelAndView mv=new ModelAndView();
        mv.addObject("mydate",request.getParameter("birthday"));
        mv.setViewName("/typeconverter.jsp");
        return mv;
    }

 

 

public class MyDateEditor extends PropertiesEditor {
    @Override
    public void setAsText(String source)throws IllegalArgumentException{
        SimpleDateFormat sdf=getDateFormate(source);

        try {
            Date date = sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    private SimpleDateFormat getDateFormate(String source) {
        SimpleDateFormat sdf=null;
        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{
            throw new TypeMismatchException("",Date.class);
        }
        return sdf;
    }
}

 

这种方式实现  从页面获取到输入的字符串,转换成日期格式,但只作用在单个的controller控制器中

 

posted @ 2017-08-28 17:33  会飞的豆子  阅读(893)  评论(0编辑  收藏  举报