简体   繁体   English

如何在javascript中从servlet传递值

[英]how to pass a value from servlet in javascript

I'm new to servlets and all this topic so sorry if it's a bit messy!我是 servlets 和所有这个主题的新手,如果它有点乱,我很抱歉! I'm trying to send a value from servlet to javascript or get value of a servlet method in java script.我正在尝试将值从 servlet 发送到 javascript 或在 java 脚本中获取 servlet 方法的值。 I'm not sure about the doGet !我不确定doGet am I doing it right ?我做得对吗? getting the value of fields and sending the result to javascript ?获取字段的值并将结果发送到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();
    }
}

I'm trying to get the value of the two input fields process on them and send the result to javascript我正在尝试获取两个输入字段的值,并将结果发送到 javascript

Servlet doGet:小服务程序 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: Servlet doPost:

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

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

Thanks In Advance!提前致谢!

you have your java right, it is request.getParameter(...).你有你的java,它是request.getParameter(...)。 However your not sending any data using javascript.但是,您没有使用 javascript 发送任何数据。 If you want to send a "GET" request then use the code you have but make the following change:如果您想发送“GET”请求,请使用您拥有的代码,但进行以下更改:

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

I would look up some JQuery tutorials on using the get and post methods.我会查找一些关于使用 get 和 post 方法的 JQuery 教程。 Also you may want to comment out that code you have and just test sending across some variables to get the hang of things before you dive right into that java side of things.此外,您可能想注释掉您拥有的代码,并在直接深入到 Java 方面之前测试发送一些变量以掌握事情的窍门。

You're not sending any parameters to the Servlet.您没有向 Servlet 发送任何参数。 Even if you do, you'll encounter an IllegalStateException .即使这样做,您也会遇到IllegalStateException It is because you're writing to the response body, using out.println() , and then setting headers.这是因为您正在写入响应正文,使用out.println() ,然后设置标题。 The statement该声明

finally {
        out.close();
 }

also flushes the output stream, preventing you from writing any response headers.还刷新输出流,防止您写入任何响应标头。

Set any headers before writing to the response body and pass the required parameters in $.get在写入响应正文之前设置任何标头并在$.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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM