protected void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HashMap hashMap = new HashMap<>();
    response.setContentType("test/json;charset=utf-8");
    //获取信息
    String disease_type = request.getParameter("disease_type");
    String describetion = request.getParameter("describetion");
    String describe_img = request.getParameter("describe_img");
    String doctor_id = request.getParameter("doctor_id");
    String user_id = request.getParameter("user_id");
    String book_time = request.getParameter("book_time");

    //非空判断
    if (disease_type == null || disease_type.isEmpty()) {
        hashMap.put("message", "疾病类型不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    if (describetion == null || describetion.isEmpty()) {
        hashMap.put("message", "描述不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    if (describe_img == null || describe_img.isEmpty()) {
        hashMap.put("message", "描述图片不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    if (doctor_id == null || doctor_id.isEmpty()) {
        hashMap.put("message", "医生ID不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    if (user_id == null || user_id.isEmpty()) {
        hashMap.put("message", "用户ID不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    if (book_time == null || book_time.isEmpty()) {
        hashMap.put("message", "预约时间不能为空");
        response.getWriter().append(gson.toJson(hashMap));
        return;
    }

    //数据封装
    Registration registration = new Registration(0, disease_type, describetion, describe_img, null, Integer.parseInt(doctor_id), Integer.parseInt(user_id), 0, book_time);
    System.out.println(registration);

    //判断及响应
    boolean insert = registrationService.insert(registration);
    if (!insert) {
        hashMap.put("message", "预约挂号出错");
    }
    hashMap.put("flag", insert);
    response.getWriter().append(gson.toJson(hashMap));
}

该代码增加了对所有关键参数的非空判断,如果参数为空,则会返回相应的错误信息。这种处理方式可以有效避免 NumberFormatException: For input string: "" 错误,并提供更友好的用户体验。

此外,建议在实际开发中进行如下优化:

  1. 错误信息处理: 可以将错误信息进行分类,例如根据错误类型返回不同的错误码和信息,方便前端进行错误处理和展示。
  2. 日志记录: 可以使用日志框架记录请求参数和错误信息,方便排查问题。
  3. 数据校验: 除了非空判断,还可以对参数进行其他校验,例如格式校验、长度校验等,以保证数据的正确性。
  4. 异常处理: 可以使用异常处理机制,将可能出现的异常进行捕获和处理,避免程序崩溃。
  5. 安全防范: 对用户输入进行安全过滤,防止 SQL 注入和 XSS 攻击等安全风险。

通过以上优化,可以确保代码的健壮性和安全性,提供更可靠的服务。


原文地址: https://www.cveoy.top/t/topic/p3Yt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录