Spring MVC中Date处理

来源:互联网 发布:公司数据库搭建 编辑:程序博客网 时间:2024/05/01 12:22

问题描述

java中的date类型 在接收前台传入的参数时报400错误。时间格式为“yyyy-MM-dd HH:mm:ss”。


问题分析

由于前端传入的参数默认为String,然后与后台接收的参数不匹配,所以浏览器报400错误。


解决方案

  • 通过String 变量来接收字符串,然后通过时间转换类DateFormatter进行转换后,得到Date对象。
@Controllerpublic class TestController(){    public void test(String dateString){        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        Date date = sdf.parse(dateString); //转换为date    }}
  • 在controller中绑定一个时间转换方法
@Controllerpublic class TestController{    @InitBinder    public void intDate(WebDataBinder dataBinder){        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));    }    public void test(Date date){        ……    }}

这样在整个controller中的所有方法在接收date类型的字符串时,都会自动转换为Date对象。为了方便使用,可以写一个基础的controller作为父类,将绑定的方法写父controller中,如:

public class BaseController{    @InitBinder    public void intDate(WebDataBinder dataBinder){        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));    }}@Controllerpublic class TestController extends BaseController{    public void test(Date date){        ……    }}