如何更新列表错误以使其显示在JSP页面上?

时间:2015-03-21 16:45:30

标签: java jsp servlets

我有点担心将单独的错误放入列表中以显示在我的JSP页面上。评论区域是我需要帮助的。我试图想一想,但我想不出要为if或else块放什么。

// Validate Parameters
            List<String> errors = validate(nationalID, lastName, firstName, dateOfBirth);

            if (errors.isEmpty()){
                // Input valid

                // Commit Edit

                // Forward to Display

            } else {
                // Input NOT valid

                // Attach errors

                // Attach old input

                // Forward to Edit.jsp
            }



private List<String> validate(String nationalID, String lastName, String firstName,
        String dateOfBirth) {

    List<String> errors = new ArrayList<>();

    if (nationalID == null || nationalID.length() != 5 || !nationalID.matches("[A-Za-z]{2}[0-9]{3}")) {
        errors.add("Please check that your National ID is in the correct format");
    }

    if (lastName.isEmpty()) {
        errors.add("Last Name cannot be empty");

    }

    if (firstName.isEmpty()) {
        errors.add("First Name cannot be empty");

    }

    try {
        LocalDate.parse(dateOfBirth);
    } catch (DateTimeParseException e) {
        errors.add("Date of Birth is not formatted correctly");

    }

    return errors;
}

1 个答案:

答案 0 :(得分:0)

RequestDispatcher dispatcher = null;
HttpSession session = request.getSession();

if (errors.isEmpty()){
            session.setAttribute("status", errors.isEmpty());
            dispatcher = getServletContext().getRequestDispatcher("/Home.jsp");
            // Write your JDBC or whatever and update your db values

        } else {

            dispatcher = getServletContext().getRequestDispatcher("/Login.jsp");
            session.setAttribute("status", errors.isEmpty());
            ArrayList<String> old_data = new ArrayList<String>();
            old_data.add(nationalID);
            old_data.add(lastName);
            old_data.add(firstName);
            old_data.add(dateOfBirth);
            session.setAttribute("old_data", old_data);


        }

        try {
               dispatcher.forward(request,response);
        } catch (ServletException e) {
               e.printStackTrace();
        }