1

我是 servlet 和所有这些主题的新手,如果有点混乱,我很抱歉!我正在尝试将值从 servlet 发送到 javascript 或在 java 脚本中获取 servlet 方法的值。我不确定doGet!我做对了吗?获取字段的值并将结果发送到javascript

小服务程序:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        String passengerCount = request.getParameter("passengerCount");
        String departureSchedule = request.getParameter("schedule");
        String arrivalSchedule = request.getParameter("returnschedule");
        HttpSession session = request.getSession(true);
        int departureSID = 0;
        int passengerCountInt = 0;
        userID = 0;
        int arrivalSID = 0;

        try {
            departureSID = Integer.parseInt(departureSchedule);
            passengerCountInt = Integer.parseInt(passengerCount);
            userID = Integer.parseInt(session.getAttribute("userID").toString());
            arrivalSID = Integer.parseInt(arrivalSchedule);
        } catch (Exception e) {
        }

        if (departureSID != 0) {
            ScheduleBean departureSb = new ScheduleBean();
            departureSb.selectSchedule(departureSID);
            int departureRoute = departureSb.getRouteID();
            RouteBean routeB1 = new RouteBean();
            routeB1.selectRoute(departureRoute);
            double routeCharge = routeB1.getCharge();
            double totalDCharge = routeCharge * passengerCountInt;
            ReservationBean rb = new ReservationBean();
            UserBean us = new UserBean();

            if (arrivalSchedule == null) {
                rb.saveOneWayReservation(departureSID, userID, totalDCharge, passengerCountInt, "TICKET");
            } else {
                departureSb.selectSchedule(arrivalSID);
                int arrivalRoute = departureSb.getRouteID();
                routeB1.selectRoute(arrivalRoute);
                double arrivalRouteCharge = routeB1.getCharge();
                totalDCharge += arrivalRouteCharge * passengerCountInt;
                rb.saveRoundReservation(departureSID, arrivalSID, userID, totalDCharge, passengerCountInt, "TICKET");
            }

            ScheduleBean sbb = new ScheduleBean();
            sbb.selectSchedule(rb.scheduleID);
            AirBean bbb = new AirBean();
            bbb.selectAir(sbb.getAirID());
            String AirCode = bbb.getAirCode();
            String username = session.getAttribute("username").toString();
            int referenceNumber = rb.reservationID + 100;

            rb.updateTicketNumber(AirCode + "-" + username + "-" + String.valueOf(referenceNumber));
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Make payment</title>");
            out.println("<script type='text/javascript' src='js/jquery-1.5.2.min.js'></script>");
            out.println("<script type='text/javascript' src='js/payment.js'></script>");
            out.println("<script src='http://code.jquery.com/jquery-latest.min.js'></script>");
            out.println("<link type='text/css' href='css/style.css' rel='Stylesheet' />");
            out.println("</head>");
            out.println("<body>");
            out.println("<div class='bg-light' style='width: 200px; height: 200px; position: absolute; left:50%; top:50%;  margin:-100px 0 0 -100px; padding-top: 40px; padding-left: 10px;'>");
            out.println("<input id='reservationID' style='display: none' value='" + rb.reservationID + "' />");
            out.println("<div>Credit Card Number : </div>");
            out.println("<div><input id='creditcard' onKeyPress='return checkIt(event);' type='text' name='creditcard' maxlength='16' /></div>");
            out.println("<div>ExpirationDate : </div>");
            out.println("<div><input id='expirationDate' type='text' onKeyPress='return checkIt(event);' name='expirationDate' maxlength='4' /></div>");
            out.println("<input type='hidden' id='FormName' name='FormName' value='" + HiddenValue + "'>");
            out.println("<div><input id='somebutton' type='button'  name='buttonsave' value='Make Payment' onclick='makePayment(" + rb.reservationID + ");' /></div>");
            out.println("<div><input type='button'  name='buttoncancel' value='Cancel Payment' onclick='cancelPayment(" + rb.reservationID + ");' /></div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        }
    } finally {
        out.close();
    }
}

我正在尝试获取对它们进行处理的两个输入字段的值并将结果发送到 javascript

Servlet doGet:

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

    creditno = request.getParameter("creditcard");       //name of the input field, not id
    expiration = request.getParameter("expirationDate");     //name of the input field should be expirationDate
    UserBean us = new UserBean();
    boolean check = us.checkCC(userID, creditno, expiration); // process the fields 
    if (check == true) {
        CCA = "1";
    } else {
        CCA = "0";
    }

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(CCA);       // Write response body.

}

Servlet doPost:

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

Javascript:

var tempresp;
$(document).ready(function() {                        // When the HTML DOM is ready loading, then execute the following function...
    $('#somebutton').click(function() {               // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
        $.get('MakeReservation', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
            alert(responseText);
            tempresp=responseText;
        });
    });
});

提前致谢!

4

2 回答 2

0

你有你的java权利,它是request.getParameter(...)。但是,您没有使用 javascript 发送任何数据。如果您想发送“GET”请求,请使用您拥有的代码,但进行以下更改:

$.get('MakeReservation?creditcard=12345&expirationDate=11%2F14', ....);

我会查找一些有关使用 get 和 post 方法的 JQuery 教程。此外,您可能希望注释掉您拥有的代码,并在直接进入 Java 方面之前测试发送一些变量以掌握事情的窍门。

于 2013-11-11T04:16:21.353 回答
0

您没有向 Servlet 发送任何参数。即使你这样做,你也会遇到一个IllegalStateException. 这是因为您正在写入响应正文,使用out.println(),然后设置标题。该声明

finally {
        out.close();
 }

还会刷新输出流,防止您写入任何响应标头。

在写入响应正文之前设置任何标头并将所需的参数传递给$.get

$.get('MakeReservation', {passengerCount: 2, arrivalSchedule: 123}, function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
          alert(responseText);
});
于 2013-11-11T04:20:52.560 回答