解决报错:Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'
发生这一错误的主要原因是Controller类中需要接收的是Date类型,但是在页面端传过来的是String类型,最终导致了这个错误。、
解决方法在InitBinder 初始化的时候对日期类型进行转换,转换为可以被接受的类型,,也可以实现全局的日期类型的转换。
其中代码如下:
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//参数true表示允许日期为空(null、"")
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
代码解释:
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//true:允许输入空值,false:不能为空值
全部代码:
package com.example.demo.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.pojo.Members;
import com.example.demo.service.MemberService;
import com.example.utils.AjaxResult;
import com.example.utils.CommonUtils;
import com.example.utils.XYFJSONResult;
/**
* 员工管理
*
* @author reborn
*
*/
@RestController
@RequestMapping("/member")
public class MemberController {
@Autowired
private MemberService service;
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//参数true表示允许日期为空(null、"")
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
/**
* 查看所有员工 返回视图
*
* @return
*/
@RequestMapping("/list.do")
public ModelAndView list(String number, @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss") Date beginTime,@DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss") Date endTime) {
/**
* 查询时间范围内的员工
*/
Map<String, Object> params = new HashMap<String, Object>();
if (number != null && number.length() > 0) {
params.put("param", "%" + number + "%");
}
params.put("beginTime", beginTime);
if (endTime != null) {
// 比如如果要查询截止到9月22注册的用户,应该查询出来9月23号零点之前的数据
endTime.setTime(endTime.getTime() + 1000 * 60 * 60 * 24 - 1);
}
params.put("endTime", endTime);
//System.out.println(params);
List<Members> list=service.search(params);
ModelAndView modelAndView = new ModelAndView("/user/list");
modelAndView.addObject("list", list);
return modelAndView;
}
}