SpringBoot学习3 - 自定义日期转换

201 阅读1分钟

文章目录

方法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;
    }
}

测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zaHVHXBC-1587871744587)(en-resource://database/26754:0)]

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";
    }
}


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-etvihHQy-1587871744597)(en-resource://database/26640:1)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FN5LXwHn-1587871744603)(en-resource://database/26642:1)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SqAjfPMX-1587871744607)(en-resource://database/26644:1)]