0
\$\begingroup\$

Image that a user have to book a private lesson by compiling this form.

enter image description here

Using MVC pattern I'm building a WebApplication to achieve this goal; I have a jsp wich contains the form and by using Ajax I want to send data to a servlet which is my controller. This servlet comunicate with a DAO and once data are taken from database, they are sent back to jsp.

Here's the code i wrote: JSP

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
              crossorigin="anonymous">

        <title>JSP Page</title>
    </head>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>

        <form action="BookingController" method="GET">
            <input type="hidden" name="command" value="show_courses"/>
            <div class="modal-header">
                <h5 class="modal-title">Book your lesson!</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <select id="course">
                    <option value="" disabled selected>Select a course</option>
                    <c:forEach var="item" items="${AVAILABLE_COURSES}">                      
                        <option data-id='${item.id}'>${item.courseName}</option>
                    </c:forEach>
                </select>
                <br>
                <br>
                <select id="teacher">
                    <option value="" disabled selected>Select teacher</option>
                </select>
                <br>
                <br>
                <select id="days">
                    <option value="" disabled selected>Select the day</option>
                    <option data-id='Monday'>Monday</option>
                    <option data-id='Friday'>Friday</option>
                </select>
                <br>
                <br>
                <select id='hour'>
                    <option value="" disabled selected>Select time</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" id="book" class="btn btn-primary">Book</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </form>

        <script type="text/javascript">

            $("#course").change(function () {
                $.ajax({
                    type: 'GET',
                    cache: false,
                    url: 'BookingController',
                    data: {
                        action: "show_teachers",
                        course: $("#course").val()
                    },
                    success: function (data) {
                        teacher = JSON.parse(data);
                        var option;
                        $("#teacher").empty();
                        for (var i in teacher) {
                            option = '<option data-id = ' + teacher[i].teacherId + '>' + teacher[i].firstNameLastName + '</option>';
                            $("#teacher").append(option);
                        }
                    }
                });
            });

            $("#days").change(function () {
                $.ajax({
                    type: 'GET',
                    cache: false,
                    url: 'BookingController',
                    data: {
                        action: "show_available_hours",
                        courseId: $("#course>option:selected").attr("data-id"),
                        teacherId: $("#teacher>option:selected").attr("data-id"),
                        day: $("#days>option:selected").attr("data-id")
                    },
                    success: function (data) {
                        hours = JSON.parse(data);
                        var option;
                        $("#hour").empty();
                        for (var i in hours) {
                            option = '<option data-id = ' + hours[i] + '>' + hours[i] + '</option>';
                            $("#hour").append(option);
                        }
                    }
                });
            });
      </script>
    </body>
 </html>

Servlet:

//@WebServlet(urlPatterns = {"/BookingController"})
public class BookingController extends HttpServlet {

    private OperationsDbUtil operationsDbUtil = null; //DAO
    private Gson gson = new Gson();

    // init for DB connection

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            // read the command parameter
            String requestedAction = request.getParameter("action");

            // if action is missing, route to the default page
            if (requestedAction == null) {
                requestedAction = "homepage";
            }

            //route to the appropriate method
            switch (requestedAction) {
                case "homepage":
                    fillBookingForm(request, response);
                    break;
                case "show_courses":
                    fillBookingForm(request, response);
                    break;
                case "show_teachers":
                    showTeachers(request, response);
                    break;
                case "show_available_hours":
                    showAvailableHours(request, response);
                    break;
                default:
                    showCatalog(request, response);
                    break;
            }

        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void fillBookingForm(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {

        // get courses list
        List<Course> coursesList = operationsDbUtil.getCourses();

        // add list to the request obj
        request.setAttribute("AVAILABLE_COURSES", coursesList);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/booking-lesson-form.jsp");

        try {
            dispatcher.forward(request, response);
        } catch (ServletException | IOException ex) {
            Logger.getLogger(BookingController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void showTeachers(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String course = null;
        if (request.getParameter("course") != null) {
            course = request.getParameter("course");
        }

        // get teachers list
        List<Teacher> teachersList = operationsDbUtil.getTeachers(course);
        response.getWriter().write(gson.toJson(teachersList));
    }

    private void showAvailableHours(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        String courseId = null;
        String teacherId = null;
        String day = null;

        String[] availableHours = {"3-4pm", "4-5pm"}; 
        List<String> hoursList = new ArrayList<>();
        hoursList.addAll(Arrays.asList(availableHours));

        if (request.getParameter("courseId") != null && request.getParameter("teacherId") != null) {
            courseId = request.getParameter("courseId");
            teacherId = request.getParameter("teacherId");
            day = request.getParameter("day");
        }

        List<String> notAvailableHoursList = operationsDbUtil.getAvailableHours(courseId, teacherId, day);
        hoursList.removeAll(notAvailableHoursList);
        response.getWriter().write(gson.toJson(hoursList));
    }
}

So this is what happens:

1) When user open the form, the database is queried and all the available courses are sent to the jsp so first field can be filled. 2) Once user has selected the desidered course, another request is sent to the servlet, the database is queried to get all the teachers available for the selected course and the list is sent back to jsp. 3) The user must select a day, there's not query about this - there are default options. 4) When day is selected, a request is sent to the servlet which queries again the database and based on the previous selection send to the jsp the available time where the lessons can be booked.

Mainly my doubts are in the part related to Ajax, I wonder if I am managing the sending and receiving of data correctly or if there is a better way to do it. I don't know if this continuous exchange of requests from the jsp could generate problems or if it is not a good practice. Any suggestions?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.