如何在javascript中从servlet传递一个值

时间:2013-11-11 04:11:56

标签: java javascript jquery ajax servlets

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

的Servlet

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;
        });
    });
});

提前致谢!

2 个答案:

答案 0 :(得分:0)

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

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

我会查看一些关于使用get和post方法的JQuery教程。此外,你可能想要注释掉你所拥有的代码,并且只是测试一些变量的发送,以便在你深入研究java方面之前掌握一些东西。

答案 1 :(得分: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);
});