首页 > 解决方案 > 我无法将日期变量传递给构造函数 - 无法解析

问题描述

在用于向数据库表添加新记录的 servlet 中,我需要将 Date 值传递给构造函数,但是如果我在构造函数参数中解析,则会收到以下错误

“未处理的异常:java.text.ParseException”

当我在将值放入构造函数之前尝试使用 try catch 进行解析时,该值被视为未初始化。

这是实体类

@Entity
@Table(name = "doctors")
@Data
public class Doctors implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Id")
    private Integer id;
    @Column(name = "Name")
    private String name;
    @Column(name = "Surname")
    private String surname;
    @Column(name = "Title")
    private String title;
    @Column(name = "LicenseNumber")
    private String licenseNumber;
    @Column(name = "Phone")
    private String phone;
    @Column(name = "Email")
    private String email;
    @Column(name = "Nationality")
    private String nationality;
    @Column(name = "Speciality")
    private String speciality;
    @Column(name = "DateofBirth")
    private LocalDate dateOfBirth;
    @Column(name = "IsaTeacher")
    private Boolean isATeacher;

    public Doctors() {
    }

    public Doctors(Integer id, String name, String surname, String title, String licenseNumber, String phone, String email, String nationality, String speciality, LocalDate dateOfBirth, Boolean isATeacher) {
        this.id = id;
        this.name = name;
        this.surname = surname;
        this.title = title;
        this.licenseNumber = licenseNumber;
        this.phone = phone;
        this.email = email;
        this.nationality = nationality;
        this.speciality = speciality;
        this.dateOfBirth = dateOfBirth;
        this.isATeacher = isATeacher;
    }
}

这是我从 http 请求中得到的值

String dateOfBirth = req.getParameter("dateOfBirth");

这些是我让它发挥作用的尝试。这个给出“未处理的异常:java.text.ParseException”

Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone, email, nationality, speciality, new SimpleDateFormat("yyyy-MM-dd").parse(dateOfBirth), Boolean.valueOf(isATeacher));

而这个“变量未初始化”

DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date1;
        try {
            date1 = simpleDateFormat.parse(dateOfBirth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone, email, nationality, speciality, date1, Boolean.valueOf(isATeacher));

我真的不知道该怎么办。我必须处理异常才能解析 String 到日期,但是在 try 块之外看不到变量。

标签: javadatejspservlets

解决方案


您的Doctors构造函数需要一个LocalDate参数,而不是 a Date(这很好,因为它属于 java.time,它是现代且更好的 Java 日期和时间 API,Date设计不佳且早已过时)。LocalDate

额外的好处是,在解析失败的情况下,解析 aLocalDate会引发未经检查的异常,而不是经过检查的异常,因此编译器不介意。

额外的额外奖励,LocalDate将您的格式 yyyy-MM-dd 解析为默认值,即没有任何显式格式化程序。这是因为该格式符合 ISO 8601 标准。

    Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone,
            email, nationality, speciality, LocalDate.parse(dateOfBirth),
            Boolean.valueOf(isATeacher));

链接


推荐阅读