文章目录
方法1 - 属性字段添加@DateTimeFormat
public class Human {
@NotEmpty(message="{human.name.notEmpty}")
String name;
// 当请求参数接收到该yyyy-MM-dd类型的字符串则自动转换成日期类型
@DateTimeFormat(pattern="yyyy-MM-dd")
Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
方法2 - 控制器内添加被@InitBinder注解修饰的Method
@InitBinder
public void convertDate(ServletRequestDataBinder servletRequestDataBinder) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
servletRequestDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf,true));
}
方法3 - 实现Converter接口、并交给容器管理 - 建议使用
@Component
public class MyDateConverter implements Converter<String, Date> {
// 日期字符串正则判断
private static final String DATE_REGEX = "^[1-2]\\d{3}-(0[1-9]|1[1-2])-(0[1-9]|[1-2]\\d|3[0-1])";
// 日期盘匹配模式
private static final String DATE_FORMAT = "yyyy-MM-dd";
// 请求参数的属性名与Bean的日期属性名对应则进入该函数进行类型转换
@Override
public Date convert(String source) {
// 如果请求参数不为空,则进入日期正则判断
if(!StringUtil.isEmpty(source)) {
// 日期字符串匹配成功
if(source.matches(DATE_REGEX)) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
try {
Date date = simpleDateFormat.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
return null;
}
}
测试
listDate.html
<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
<meta charset="UTF-8" >
<title>Title</title>
</head>
<body>
<table border="1">
<thead>
<th>姓名</th>
<th>出生日期</th>
</thead>
<tbody >
<tr th:each="human:${humans}">
<td th:text="${human.name}"></td>
<td th:text="${#dates.format(human.date,'yyyy-MM-dd')}"></td>
</tr>
</tbody>
</table>
<a th:href="@{/dates/add}">添加日期</a>
</body>
</html>
addDate.html
<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/dates/add}" method="post">
姓名:<input type="text" name="name" />
<span th:if="${errors != null}" th:text="${errors.fieldErrors[0].defaultMessage}"></span>
<br>
日期:<input type="text" name="date" />
<br>
<input type="submit" value="添加日期">
</form>
</body>
</html>
控制器
@Controller
@RequestMapping(value="dates")
public class DateController {
List<Human> humans = new ArrayList<Human>();
@GetMapping
public String listUI(Model model) {
model.addAttribute("humans", humans);
return "/date/listDate";
}
@GetMapping("add")
public String addUI() {
return "date/addDate";
}
@PostMapping("add")
public String add(@Validated Human human, Errors errors, Model model) {
model.addAttribute("errors", errors);
if(errors.hasErrors()) {
List<FieldError> fieldErrors = errors.getFieldErrors();
for(FieldError error : fieldErrors) {
System.out.println(error.getField() + "==========" + error.getDefaultMessage());
}
return "/date/addDate";
}
humans.add(human);
return "redirect:/dates";
}
}