java - 如何在Spring Boot中拒绝请求中的3位数字时间?

标签 java spring date spring-boot date-parsing

我是 Java 新手。我在 json 中获取以下格式的日期和时间,

{
   "appointmentDate":"2017-05-30",
   "appointmentTime":"23:30:00"
}

在请求中,我正在这样做,

    @NotNull(message = "appointmentDate is required")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date appointmentDate;

    @NotNull(message = "appointmentTime is required")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
    private String appointmentTime;

在上面的请求类中,我使用 Date 类来获取日期并将时间视为字符串。

然后在服务类中,我尝试将字符串对象转换为日期对象,然后在表中搜索以查找表中的约会列表。

    // convert into string
    String dateString = null;
    SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd");
    dateString = sdfr.format( appointmentDate );
    String dt = dateString + " " + appointmenTime;
    Date startDateAndTime = null;
    try {
        //startDateAndTime = yyyyMMddFormat.parse(yyyyMMddFormat.format(dt));
         startDateAndTime = new SimpleDateFormat(Constants.DATEANDTIME).parse(dt);  
    } catch (ParseException e) {
        throw new IllegalArgumentException("Illegal date format");
    }

但我面临的问题是,即使我输入了错误的日期,它也会给我输出。日期中的错误不会引发解析异常。

    {
       "appointmentDate":"20171-05-30",
       "appointmentTime":"231:30:00"
    }

这是我的常量

public static final String DATEANDTIME = "yyyy-MM-dd HH:mm:ss";

这是我的存储库查询,

    @Query(value = "select COUNT(a.doctorId)  from Appointment a WHERE a.doctorId = :doctorId AND a.scheduleFromTime = :appointmentDateTime")
    Long findAppointmentExists(@Param("doctorId") Long doctorId,
            @Param("appointmentDateTime") Date appointmentDateTime);

最佳答案

请允许我建议您使用现代类 LocalDateLocalTime 来表示日期和时间。那么就很简单了,例如

if (appointmentDate.isAfter(LocalDate.now().plusYears(5)) {
    throw new IllegalArgumentException("Too far into the future");
}

这将捕获年份值中的 5 位数年份和许多其他错误。请自行设定适当的限制。您也可以类似地禁止过去的日期,也许有更严格的限制。目前这将是内置的,因为 LocalTime 只接受 23:59:59.999999999 以内的时间。

将两者合并为一个对象

LocalDateTime startDateAndTime = LocalDateTime.of(appointmentDate, appointmentTime);

我已经凭空输入了代码片段,可能有一两个拼写错误。如果无法修复,请恢复。

我最近没有使用 Spring Boot 的经验。在这个问题中,有更多关于使用现代 Java 日期和时间类与 Spring Boot 和 Jackson 的信息:JSON Java 8 LocalDateTime format in Spring Boot 。毫无疑问,在其他地方更是如此。

关于java - 如何在Spring Boot中拒绝请求中的3位数字时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511936/

相关文章:

java - 由于后台线程,tomcat 无法重新加载上下文

python - 为什么 offsets.QuarterBegin 日期是 12-01、03-01、06-01、09-01?

java - hsqldb *.script.new 创建和删除

java - JMenuItem 的 ActionListener 不起作用

java - 有没有用于域名查找的java库?

spring - 如何在一个Spring Boot java配置类(@Configuration)中创建多个bean(相同类型)?

java - 无法检索亚马逊凭据

mysql - 如何选择 >= 1 天前的行?

java - Date.toString() 给出的年份与设定的年份不同?

java - 监视和控制远程 Java 服务器