servlet 问题中无法检索 Ajax 请求参数

发布于 2024-12-10 05:41:11 字数 4519 浏览 0 评论 0原文

作为学习 Ajax 的一部分,我创建了一个小 servlet + 一些 HTML 页面 + Javascript 代码。该页面包含几个按钮。这个想法是根据按下的按钮在请求中传递参数值并在响应中返回该值。没什么疯狂的。

这是发出请求的函数(按钮在单击时链接到此函数):

function loadXMLDoc2() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","/WebFront/Ajaxlet",true);
    var retr = this.id;
    var param = "cmd=" + retr;
    document.getElementById("L1_LEFT").innerHTML = param;
    xmlhttp.send(param);
}

L1_LEFT 元素允许我检查构造的参数(例如:cmd=bd_info) 。

在 servlet 端调用以下方法来处理请求和响应:

private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

    Enumeration<String> iter = req.getParameterNames();

    System.out.println("Parameters=");
    while (iter.hasMoreElements()) {
        String next = iter.nextElement();
        System.out.println(next);
    }

    ...

}

但是,每次单击按钮时,都会打印出额外的参数行:

Parameters=
Parameters=
Parameters=
Parameters=
...

为什么?我做错了什么?

编辑

按照BalusC的解决方案,我修改了我的代码如下:

var retr = this.id;
var param = "cmd=" + encodeURIComponent(retr);
document.getElementById("L1_LEFT").innerHTML = param;
xmlhttp.open("POST","/WebFront/Ajaxlet",true);
xmlhttp.send(param);

GET

    Map<String, String[]> en = req.getParameterMap();

    System.out.println("Parameters=");
    for (String next : en.keySet()) {
        System.out.println(next);
    }

解决方案有效,但POST解决方案不起作用(同样的问题)。我读到 POST 比 GET 更好。有人知道为什么 POST 不起作用吗?

编辑 II

这是 servlet 代码:

@WebServlet(name="Ajaxlet", urlPatterns={"/Ajaxlet"}, asyncSupported=false)
public class Ajaxlet extends HttpServlet {

    private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

        Map<String, String[]> en = req.getParameterMap();

        System.out.println("Parameters=");
        for (String next : en.keySet()) {
            System.out.println(next);
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println(System.currentTimeMillis());
        out.close();        

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("doPost");
        setAnswer2(req, res);

    }

}

编辑 III

这是我的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
    <servlet>
        <display-name>Ajaxlet</display-name>
        <servlet-name>Ajaxlet</servlet-name>
        <servlet-class>net.test.Ajaxlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Ajaxlet</servlet-name>
        <url-pattern>/Ajaxlet/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

和我的 context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/WebFront"/>

编辑 IV< /strong>

将我的 web.xml 更新为:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"> 

    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

POST 仍然存在相同的问题。

As part of learning Ajax, I have created a little servlet + some HTML page + Javascript code. The page contains a couple of buttons. The idea is to pass a parameter value in a request according to the pressed button and return the value in the response. Nothing crazy.

Here is the function making the request (button are linked to this function on click):

function loadXMLDoc2() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","/WebFront/Ajaxlet",true);
    var retr = this.id;
    var param = "cmd=" + retr;
    document.getElementById("L1_LEFT").innerHTML = param;
    xmlhttp.send(param);
}

The L1_LEFT element allows me to check the constructed parameter (for example: cmd=bd_info).

The following method is called on the servlet side to proceed the request and response:

private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

    Enumeration<String> iter = req.getParameterNames();

    System.out.println("Parameters=");
    while (iter.hasMoreElements()) {
        String next = iter.nextElement();
        System.out.println(next);
    }

    ...

}

However, each time I click on buttons, I get an extra parameter line printed:

Parameters=
Parameters=
Parameters=
Parameters=
...

Why? What am I doing wrong?

EDIT

Following BalusC's solution, I modified my code as following:

var retr = this.id;
var param = "cmd=" + encodeURIComponent(retr);
document.getElementById("L1_LEFT").innerHTML = param;
xmlhttp.open("POST","/WebFront/Ajaxlet",true);
xmlhttp.send(param);

and

    Map<String, String[]> en = req.getParameterMap();

    System.out.println("Parameters=");
    for (String next : en.keySet()) {
        System.out.println(next);
    }

The GET solution works, but the POST solution does not work (same issue). I read that POST is preferable to GET. Anyone knows why POST would not work?

EDIT II

Here is the servlet code:

@WebServlet(name="Ajaxlet", urlPatterns={"/Ajaxlet"}, asyncSupported=false)
public class Ajaxlet extends HttpServlet {

    private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

        Map<String, String[]> en = req.getParameterMap();

        System.out.println("Parameters=");
        for (String next : en.keySet()) {
            System.out.println(next);
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println(System.currentTimeMillis());
        out.close();        

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("doPost");
        setAnswer2(req, res);

    }

}

EDIT III

Here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
    <servlet>
        <display-name>Ajaxlet</display-name>
        <servlet-name>Ajaxlet</servlet-name>
        <servlet-class>net.test.Ajaxlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Ajaxlet</servlet-name>
        <url-pattern>/Ajaxlet/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

and my context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/WebFront"/>

EDIT IV

Updated my web.xml to:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"> 

    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Still having the same issue with POST.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悟红尘 2024-12-17 05:41:12

您正在创建 GET 请求,然后在请求正文中发送参数。这是行不通的。为了在请求正文中发送数据,您必须创建一个 POST 请求(并在 servlet 的 doPost() 方法中而不是 doGet()):

xmlhttp.open("POST", "/WebFront/Ajaxlet", true);
xmlhttp.send(param);

在 GET 请求中,您通常将带有参数的查询字符串附加到请求 URL,而不是请求正文:

xmlhttp.open("GET", "/WebFront/Ajaxlet?" + param, true);
xmlhttp.send(null);

无论采用哪种请求方法,您都应该确保参数名称和值经过正确的 URL 编码!您可以使用 JS 的内置 encodeURIComponent() 函数来实现此目的:

var param = "cmd=" + encodeURIComponent(retr);

与具体问题无关,我知道您正在学习 Ajax,但我建议您毕竟要学习一下看看现有的 JavaScript 库,它从您手中获取发送 Ajax 请求和遍历/操作 HTML DOM 的所有令人讨厌的跨浏览器敏感细节,例如 jQuery。在此相关问题中,您可以找到一些如何开始使用 jQuery + Servlet 的很好的示例:如何使用 Servlet 和 Ajax?

另一个不相关的注意事项,您应该更喜欢使用 getParameterMap() 来迭代参数名称和值。它返回一个Map而不是老式的EnumerationMap 允许您使用增强的 for 循环。

You're creating a GET request and then sending the parameter in the request body. This isn't going to work. In order to send data in the request body, you have to create a POST request (and do the server side request processing job in servlet's doPost() method instead of doGet()):

xmlhttp.open("POST", "/WebFront/Ajaxlet", true);
xmlhttp.send(param);

On GET requests, you normally append the query string with the parameters to the request URL, not the request body:

xmlhttp.open("GET", "/WebFront/Ajaxlet?" + param, true);
xmlhttp.send(null);

Regardless of the request method, you should ensure that parameter names and values are properly URL encoded! You can use JS' builtin encodeURIComponent() function for this:

var param = "cmd=" + encodeURIComponent(retr);

Unrelated to the concrete problem, I know that you're learning Ajax, but I suggest to after all take a look at an existing JavaScript library which takes all the nasty and cross browser sensitive details of sending Ajax requests and traversing/manipulating the HTML DOM from your hands, such as jQuery. In this related question you can find some nice examples how to get started with jQuery + Servlets: How to use Servlets and Ajax?

Another unrelated note, you should prefer getParameterMap() to iterate over parameter names and values. It returns a Map instead of an old fashioned Enumeration; a Map allows you to use the enhanced for loop.

梦旅人picnic 2024-12-17 05:41:12

有完全相同的问题,为了文档的缘故,解决方案是在我的 Javascript 代码中,

当在 AJAX 帖子中发送“表单数据”时,您需要设置一个标头,如下所示..

xmlhttp.setRequestHeader("Content-type" ,“应用程序/x-www-form-urlencoded”)
xmlhttp.send("paramName=paramValue")

来源:http://www.w3schools .com/ajax/ajax_xmlhttprequest_send.asp

Had exactly this same problem, for documentations sake the solution was in my Javascript code,

When sending "form data" in your AJAX Post, you need to set a header like so..

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xmlhttp.send("paramName=paramValue")

source: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文