RESTful Api и Maven - PullRequest
       10

RESTful Api и Maven

1 голос
/ 06 мая 2020

Я пытаюсь создать часть для вставки данных с помощью crud. Я не получаю никаких ошибок, но данные не вставляются в базу данных. соединение с базой данных работает правильно. это то, что я пробовал. в таблице 5 полей: id, врач, пациент, дата и место проведения. Я не получаю никаких ошибок в консоли, но ошибка при вставке данных отображает эту строку

$("#alertError").text("Error while saving."); 

jsp файл

<html>
<head>
<meta charset="ISO-8859-1">
<title>Appointments</title>
<link rel="stylesheet" href="Views/bootstrap.min.css">
<script src="Components/jquery-3.2.1.min.js"></script>
<script src="Components/appointment.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-6">
                <h1>Appointment Management</h1>
                <br>
                <form id="formAppointment" name="formAppointment"
                action="view.jsp">
                    Appointment ID <input id="appointmentId" name="appointmentId"
                        type="text" class="form-control form-control-sm"> <br>
                    Assign Doctor <input id="assignDoctor" name="assignDoctor"
                        type="text" class="form-control form-control-sm"> <br>
                    Assign Patient <input id="assignPatient" name="assignPatient"
                        type="text" class="form-control form-control-sm"> <br>
                    Appointment Date <input id="appointmentDate" name="appointmentDate"
                        type="text" class="form-control form-control-sm"> <br>
                    Appointment Venue <input id="appointmentVenue"
                        name="appointmentVenue" type="text"
                        class="form-control form-control-sm"> <br> 

                        <input
                        id="btnSave" name="btnSave" type="button" value="Insert Appointment"
                        class="btn btn-primary">
                        <input type="hidden" id="hide" name="hide" value="">

                        <input type="submit"
                        id="btnView" name="btnView" type="button" value="View Appointment"
                        class="btn btn-primary">
                </form>
                <br>
</body>
</html>

Java файл

public class Appointment {

    public String insertAppointment(String date, String venue, String docName, String patientId) {
        String output = "";
        try {
            Connection con = connect();
            if (con == null) {
                return "Error while connecting to the database for inserting appoinment details.";
            }

            String insert = " insert into appointment (`app_Date`,`app_Venue`,`app_Doctor_Id`,`app_Patient_Id`) values (?,?,?,?)";
            PreparedStatement preparedStatement = con.prepareStatement(insert);

            preparedStatement.setString(1, date);
            preparedStatement.setString(2, venue);
            preparedStatement.setString(3, docName);
            preparedStatement.setString(4, patientId);

            preparedStatement.execute();

            output = "Inserted successfully";

            //output = "{\"status\":\"success\", \"data\": \"\"}";

        } catch (Exception e) {
            output = "Error while inserting the Appoinment.";
            System.err.println(e.getMessage());
        }
        return output;
    }

}

API

/**
 * Servlet implementation class AppointmentAPI
 */
@WebServlet("/AppointmentAPI")
public class AppointmentAPI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Appointment appointmentObj = new Appointment();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AppointmentAPI() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String output = appointmentObj.insertAppointment(request.getParameter("appointmentDate"),
                request.getParameter("appointmentVenue"), request.getParameter("assignDoctor"),
                request.getParameter("assignPatient"));

        response.getWriter().write(output);
    }

}

Проверка выполняется JavaScript

$(document).ready(function() {
    $("#alertSuccess").hide();

    $("#alertError").hide();
});
$(document).on("click", "#btnSave", function(event) {
    $("#alertSuccess").text("");
    $("#alertSuccess").hide();
    $("#alertError").text("");
    $("#alertError").hide();

    var status = validateItemForm();
    if (status != true) {
        $("#alertError").text(status);
        $("#alertError").show();
        return;
    }

    var type = ($("#hide").val() == "") ? "POST" : "PUT";

    $.ajax({
        url : "AppointmentsAPI",
        type : type,
        data : $("#formAppointment").serialize(),
        dataType : "text",
        complete : function(response, status) {
            saveAppointment(response.responseText, status);
        }
    });
});

function saveAppointment(response, status) {
    if (status == "success") {
        var resultSet = JSON.parse(response);

        if (resultSet.status.trim() == "success") {
            $("#alertSuccess").text("Successfully saved.");
            $("#alertSuccess").show();

            $("#divAppointmentsGrid").html(resultSet.data);
        } else if (resultSet.status.trim() == "error") {
            $("#alertError").text(resultSet.data);
            $("#alertError").show();

        }
    } else if (status == "error") {
        $("#alertError").text("Error while saving.");
        $("#alertError").show();
    } else {
        $("#alertError").text("UnKnown error while saving..");
        $("#alertError").show();
    }

    $("#hide").val("");
    $("#formAppointment")[0].reset();

}
function validateItemForm()
{
    /*if ($("#appointmentId").val().trim() == "")
    {
        return "Enter Appointment ID";
    }*/

    if ($("#assignDoctor").val().trim() == "")
    {
        return "Enter Doctor Id";
    }

    if ($("#assignPatient").val().trim() == "")
    {
        return "Enter Patient Id";
    }

    if ($("#appointmentVenue").val().trim() == "")
    {
        return "Enter Appointment Venue";
    }
    return true;
    }

1 Ответ

0 голосов
/ 06 мая 2020

В вашем проекте отсутствует mysql зависимость коннектора.

Если это проект maven, добавьте это в dependencies в pom. xml

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.13</version>
</dependency>

Если это не проект maven, затем загрузите эту банку и включите в папку lib. https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.13/mysql-connector-java-5.1.13.jar

PS - Проверить версию

...