首页 > 技术文章 > @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 前台request 获取body的格式是正确的 (2018-03-23 16:44:22) 但是Java 后台却格式化成了yyyy-MM-dd的格式 巨坑(@InitBinder搞得贵)

ANCAN-RAY 2018-03-23 17:40 原文

 

最近做项目时,同事写的功能总是格式化时间不正确,Java类属性明明注解了@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")  但就是硬生生的被格式化成了2018-03-23,原来是同事居然写了@InitBinder

1.实体类

public class WorkTodoDO implements Serializable {
    private static final long serialVersionUID = 1L;

    // 编号
    private Long id;
    // 标题简述
    private String title;
    // 提醒日期 将前台的字符串格式 格式化成日期类型
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date remindDate;
    // 事件性质
    private String type;
    // 级别:是否是重要时间 1:重要,2:普通
    private Integer level;
    // 到期时间
    private Date endDate;
    // 提醒方式 1:短信, 2:邮件,3:所有都提示
    private String remindType;
    // 用户id
    private Long userId;
    // 创建时间
    private Date createDate;
    // 修改时间
    private Date updateDate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getRemindDate() {
        return remindDate;
    }

    public void setRemindDate(Date remindDate) {
        this.remindDate = remindDate;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getRemindType() {
        return remindType;
    }

    public void setRemindType(String remindType) {
        this.remindType = remindType;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

    @Override
    public String toString() {
        return "WorkTodoDO [id=" + id + ", title=" + title + ", remindDate=" + remindDate + ", type=" + type
                + ", level=" + level + ", endDate=" + endDate + ", remindType=" + remindType + ", userId=" + userId
                + ", createDate=" + createDate + ", updateDate=" + updateDate + "]";
    }

}

2.前台使用的是bootstrap,日期格式化也是YYYY-MM-DD hh:mm:ss,正常form表单提交

html: 

<input id="remindDate" name="remindDate" class="laydate-icon layer-date form-control col-sm-1" onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})" placeholder="提醒日期" readonly="readonly" style="background-color: #fff; border:1px dashed #cbd5dd;" type="text" value="" /> </div>

JS代码:


function save() { $("#remindStr").val($("#remindDate").val()); $("#form_submit").attr("disabled", true); $.ajax({ cache : true, type : "POST", url : prefix + "/save", data : new FormData($('#signupForm')[0]),// 你的formid async : false, processData: false, contentType: false, error : function(request) { parent.layer.alert("Connection error"); $("#form_submit").attr("disabled", false); }, success : function(data) { if (data.code == 0) { parent.layer.msg("操作成功"); parent.reLoad(); var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引 parent.layer.close(index); } else { parent.layer.alert(data.msg) $("#form_submit").attr("disabled", false); } } }); }

3.controller代码


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
@RequestMapping("oa/todo")
public class WorkTodoController extends BaseController {

  private static final Logger LOG = LoggerFactory.getLogger(WorkTodoController.class);

  @Autowired
  private WorkTodoService todoService;

  @GetMapping()
  // @RequiresPermissions("oa:todo:todo")
  String todo() {
    return "oa/todo/todo";
  }

  @ResponseBody
  @RequestMapping("/list")
  // @RequiresPermissions("oa:todo:todo")
  public PageUtils lsit(@RequestParam Map<String, Object> params) {
    Query query = new Query(params);
    todoService.list(query);
    query.put("userId", getUserId());
    return todoService.list(query);
  }



  /**
   * 
   *
   * @param binder
   */
  @InitBinder
  public void init(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class,
        new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));

  }

  /**
   * 保存
   *
   * @param workTodoDO
   * @return
   */
  @ResponseBody
  @PostMapping("/save")
  // @RequiresPermissions("oa:todo/add")
  public R save(WorkTodoDO workTodoDO) {
    workTodoDO.setUserId(getUserId());
    if (todoService.save(workTodoDO) > 0) {
      return R.ok();
    }

    return R.error();
  }

  

}

以上就是全部代码。乍一看没什么问题(标红的地方是候来才看到的......欲哭无泪啊)

这里就是这个 @InitBinder 起了作用,他是做表单数据解析绑定的(可以绑定多个不同的实体类),具体场景请参照:

https://blog.csdn.net/xsf1840/article/details/73556633

 

推荐阅读