JSP飞机座位布局

时间:2017-07-16 19:34:55

标签: java jquery ajax jsp servlets

我正在尝试开发一个实验性的Java Web应用程序,用于通过JSP座位布局预订座位。我在24个座位上使用布尔数组,通过单击JSP页面中表单中的按钮来选择座位。
indexRevA.jsp

indexRevA.jsp using Chrome

JSP页面如下:

JSP页面indexRevA.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="model.manager.SeatManager" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <div> 
            <form name="chooseSeat" action="BookingServlet" method="GET">
                <table cellpadding="0" cellspacing="0" border="0" id="table" class="sortable">
                                            <tbody>
                        <tr>
                            <td>
                                <input type="submit" value="seat00F" name="submit" id="seat00F" /></td>
                            <td>
                                <input type="submit" value="seat03F" name="submit" id="seat03F" /></td>
                            <td>
                                <input type="submit" value="seat06F" name="submit" id="seat06F" /></td>
                            <td>
                                <input type="submit" value="seat09F" name="submit" id="seat09F" /></td>
                            <td>
                                <input type="submit" value="seat12E" name="submit" id="seat12E" /></td>
                            <td>
                                <input type="submit" value="seat15E" name="submit" id="seat15E" /></td>
                            <td>
                                <input type="submit" value="seat18E" name="submit" id="seat18E" /></td>
                            <td>
                                <input type="submit" value="seat21E" name="submit" id="seat21E" /></td>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" value="seat01F" name="submit" id="seat01F"/></td>
                            <td>
                                <input type="submit" value="seat04F" name="submit" id="seat04F"/></td>
                            <td>
                                <input type="submit" value="seat07F" name="submit" id="seat07F"/></td>
                            <td>
                                <input type="submit" value="seat10F" name="submit" id="seat10F"/></td>
                            <td>
                                <input type="submit" value="seat13E" name="submit" id="seat13E"/></td>
                            <td>
                                <input type="submit" value="seat16E" name="submit" id="seat16E"/></td>
                            <td>
                                <input type="submit" value="seat19E" name="submit" id="seat19E"/></td>
                            <td>
                                <input type="submit" value="seat22E" name="submit" id="seat22E"/></td>
                        </tr>
                        <tr>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                            <th><h3></h3></th>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" value="seat02F" name="submit" id="seat02F"/></td>
                            <td>
                                <input type="submit" value="seat05F" name="submit" id="seat05F"/></td>
                            <td>
                                <input type="submit" value="seat08F" name="submit" id="seat08F"/></td>
                            <td>
                                <input type="submit" value="seat11F" name="submit" id="seat11F"/></td>
                            <td>
                                <input type="submit" value="seat14E" name="submit" id="seat14E"/></td>
                            <td>
                                <input type="submit" value="seat17E" name="submit" id="seat17E"/></td>
                            <td>
                                <input type="submit" value="seat20E" name="submit" id="seat20E"/></td>
                            <td>
                                <input type="submit" value="seat23E" name="submit" id="seat23E"/></td>
                        </tr>
                    </tbody>

                </table><br />
                <input type="radio" value="ADULT" name="Passenger" checked="checked"/><p>Adult</p>
                <input type="radio" value="CHILD" name="Passenger" /><p>Child</p>
                <input type="radio" value="INFANT" name="Passenger" /><p>Infant</p>
            </form>

            <h3><%= request.getAttribute("seats")%></h3>
        </div>
                </body>
</html>

它提交了对Servlet的选择,如下所示:

Servlet BookingServlet

package controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.enums.PassengerEnum;
import model.enums.SeatEnum;
import model.enums.SeatTypeEnum;
import model.manager.SeatManager;

/**
 * Alba Airways application M813-TMA02-ChooseSeat
 *
 * @author james chalmers Open University F6418079
 */
@WebServlet(name = "BookingServlet", urlPatterns = {"/BookingServlet"})
public class BookingServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    SeatManager seatManager;

    private int seatNumber;
    private SeatTypeEnum seatType;
    private String msg = "";
    private String url = "";
    private String returnVal;

    /*
     * Creates a new instance of CustomerManager
     */
    @Override
    public void init() throws ServletException {
        seatManager = new SeatManager();

    }

    public void chooseSeat(HttpServletRequest request, HttpServletResponse response) {
        if (seatManager.checkNotFullyBooked()) {

            url = "/indexRevA.jsp";
            String passenger = request.getParameter("Passenger");
            boolean isSeatBooked = false;
            if (seatManager.getSeats()[seatNumber] == true) {
                msg = "This seat is already booked. Please choose another seat.";
                request.setAttribute("msg", msg);
                url = "/booked.jsp";
            } else {
                seatManager.assignSeat(seatNumber, seatType);
                isSeatBooked = true;
                returnVal = "color:red";
                request.setAttribute("returnVal", returnVal);
                msg = "Your Seat Booking.";
                for (SeatEnum seatEnum : SeatEnum.values()) {
                    if (seatNumber == seatEnum.ordinal()) {
                        if (passenger.equals(PassengerEnum.ADULT.toString())) {
                            double seatCost = SeatEnum.valueOf(seatEnum.toString()).getAdultFare();
                            request.setAttribute("seatCost", seatCost);
                        } else if (passenger.equals(PassengerEnum.CHILD.toString())) {
                            double seatCost = SeatEnum.valueOf(seatEnum.toString()).getChildFare();
                            request.setAttribute("seatCost", seatCost);
                        } else if (passenger.equals(PassengerEnum.INFANT.toString())) {
                            double seatCost = SeatEnum.valueOf(seatEnum.toString()).getInfantFare();
                            request.setAttribute("seatCost", seatCost);
                        }
                        request.setAttribute("passengerType", passenger);
                        request.setAttribute("seatNumber", seatNumber);
                        request.setAttribute("seatType", seatType);
                    }
                    request.setAttribute("msg", msg);
                    request.setAttribute("seats", Arrays.toString(seatManager.getSeats()));

                }

                url = "/message.jsp";
            }
            try (FileOutputStream fos = new FileOutputStream("C:\\Users\\user\\Documents\\seats.ser");
                    ObjectOutputStream oos = new ObjectOutputStream(fos)) {
                oos.writeObject(seatManager.getSeats());
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.getMessage();
            }
        } else {
            msg = "The Flight is fully booked. Please choose another Flight.";
            request.setAttribute("msg", msg);
            url = "/booked.jsp";
        }
    }

    /**
     * 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 {

        request.setAttribute("seats", Arrays.toString(seatManager.getSeats()));
        //request.setAttribute("returnVal", returnVal);
        String submit = request.getParameter("submit");
        if (submit != null && submit.length() > 0) {

            if (submit.equals("seat00F")) {
                seatNumber = 0;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat01F")) {
                seatNumber = 1;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat02F")) {
                seatNumber = 2;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat03F")) {
                seatNumber = 3;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat04F")) {
                seatNumber = 4;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat05F")) {
                seatNumber = 5;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat06F")) {
                seatNumber = 6;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat07F")) {
                seatNumber = 7;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat08F")) {
                seatNumber = 8;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat09F")) {
                seatNumber = 9;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat10F")) {
                seatNumber = 10;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat11F")) {
                seatNumber = 11;
                seatType = SeatTypeEnum.FIRSTCLASS;
                chooseSeat(request, response);
            } else if (submit.equals("seat12E")) {
                seatNumber = 12;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat13E")) {
                seatNumber = 13;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat14E")) {
                seatNumber = 14;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat15E")) {
                seatNumber = 15;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat16E")) {
                seatNumber = 16;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat17E")) {
                seatNumber = 17;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat18E")) {
                seatNumber = 18;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat19E")) {
                seatNumber = 19;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat20E")) {
                seatNumber = 20;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat21E")) {
                seatNumber = 21;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat22E")) {
                seatNumber = 22;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seat23E")) {
                seatNumber = 23;
                seatType = SeatTypeEnum.ECONOMY;
                chooseSeat(request, response);
            } else if (submit.equals("seats")) {
                url = "/indexRevA.jsp";
            }
        }
        RequestDispatcher dispatcher
                = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

我需要的是用户在选择座位时告知哪些座位被预订的方式。有没有办法根据是否已预订更改按钮颜色?我是JavaScript的新手,这也是我打砖墙的原因!我的Seat Manager课程如下所示:

SeatManager类

package model.manager;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Random;
import model.enums.SeatTypeEnum;

/**
 *
 * @author james
 */
public class SeatManager implements Serializable {

    private static final long serialVersionUID = 1L;

    private final int NUMBER_OF_SEATS = 24;
    private boolean[] seats;
    private int firstClassCounter;//counter for first class
    private int economyCounter;//counter for economy class
    private boolean isSeatBooked;
    Random randomNumber = new Random();

    public SeatManager() {

        this.seats = new boolean[NUMBER_OF_SEATS];//RESETS Seats TO FALSES
        this.seats = initSeats();

    }

    private boolean[] initSeats() {

        try (FileInputStream fis = new FileInputStream("C:\\Users\\user\\Documents\\seats.ser");
                ObjectInputStream in = new ObjectInputStream(fis)) {
            in.readObject();
            //String seatsString = (String) in.readObject();

            seats = (boolean[]) in.readObject();
            in.close();
        } catch (ClassNotFoundException | IOException e) {
            e.getMessage();
        }
        return seats;
    }

    public int getNUMBER_OF_SEATS() {
        return NUMBER_OF_SEATS;
    }

    public boolean[] getSeats() {
        return seats;
    }

    public int getFirstClassCounter() {
        return firstClassCounter;
    }

    public int getEconomyCounter() {
        return economyCounter;
    }

    public boolean isIsSeatBooked() {
        return isSeatBooked;
    }

    public boolean checkNotFullyBooked() {
        for (int i = 0; i < seats.length; i++) {
            if (seats[i] = true) {
                return true;
            }
        }
        return false;
    }

    public static boolean areAllSeatsBooked(boolean[] seats) {
        for (boolean b : seats) {
            if (!b) {
                return false;
            }
        }
        return true;
    }

    public boolean[] assignSeat(int seatNumber, SeatTypeEnum seatType) {
        if (seatType == SeatTypeEnum.ECONOMY) {
            economyCounter++;
            if (economyCounter > 12) {
                System.out.println("All the Economy seats have been used up.");
            }

        } else if (seatType == SeatTypeEnum.FIRSTCLASS) {
            firstClassCounter++;
            if (firstClassCounter > 12) {
                System.out.println("All the First Class seats have been used up.");
            }

        }

        seats[seatNumber] = true;
        return seats;
    }

修改

的jQuery 这是我对AJAX的第一次尝试 - 我想打电话给Servlet并获得一系列座位预订。它几乎可以工作 - 它根据DOM索引错误地匹配座位选择,而不是基于行的座位布局。

   <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "get",
                url: "BookingServlet",
                dataType: 'json',
                error: function () {
                    alert("Error Occurred");
                },
                success: function (data) {
                    var receivedData = [];
                    $.each(data.jsonArray, function (index) {
                        $.each(data.jsonArray[index], function (key, value) {
                            var point = [];
                            point.push(key);
                            point.push(value);
                            receivedData.push(point);
                            document.getElementById("output").innerHTML = point;
                            $.each(document.getElementsByClassName("btn"), function (index) { 
                                //var x = [Array.from(document.getElementsByClassName("btn")[index].id)];
                                //document.getElementsByClassName("btn")[index].id;
                                $.each(point[1], function (index, value) {
                                    if (value === true) {
                                        document.getElementsByClassName("btn")[index].style.color = "red";//
                                    }
                                });
                            }
                            );
                        });
                    });
                }
            });
        });
    </script>

AJAXServlet

    package controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.manager.SeatManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 * @author james
 */
@WebServlet(name = "AJAXServlet", urlPatterns = {"/AJAXServlet"})
public class AJAXServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    SeatManager seatManager;

    // <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 {

        response.setContentType("application/json;charset=utf-8");

        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject member = new JSONObject();

        member.put("arrayData", seatManager.getSeats());
        array.add(member);

        json.put("jsonArray", array);

        try (PrintWriter pw = response.getWriter()) {
            pw.print(json.toString());
        }
    }

下一步是找到一种随机选择空置经济座位的方法(即在12到23之间)。我做了其他一切。

1 个答案:

答案 0 :(得分:1)

这意味着您需要前端服务器的一些信息:

  

我需要的是一种让用户知道何时预订哪些座位的方法   他选择了一个座位。

为了使这项工作,你几乎没有技巧:

  1. 的WebSocket。这可以作为服务器和客户端之间的双向连接,因此当其他用户预订座位时,您将获得前端的注释。我认为这是最好的解决方案。
  2. 你可以从前端调用ajax请求但不能立即响应。仅当您预订的座位状态发生变化时,服务器才会发送响应。这是一种破解并依赖于最大会话长度
  3. 每隔几秒钟调用Ajax以了解是否有任何更改。这种方法很疯狂:)。它会产生大量的调用开销。你应该试着避免这种情况。
  4. 从服务器获取数据后,由您决定如何处理预订的座位。您可以为它们着色,或使用javascript代码进行任何弹出等

    顺便说一句,布尔值不是座位数组的最佳类型。想想像Seat这样的新课程。它可以包含行号,座位字母标记,紧急入口等。