request.getParameter() 在使用 $.ajax 和 JSON 对象作为数据时返回 null [英] request.getParameter() returns null when using $.ajax with JSON object as data

查看:17
本文介绍了request.getParameter() 在使用 $.ajax 和 JSON 对象作为数据时返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java servlet,我为GET"和POST"编写了两个单独的 servlet.当GET"请求发送到服务器时,servlet 访问数据库并检索所有内容并将结果转换为 Google Charts 可以识别的格式.当POST"请求发送到服务器时,servlet 获取参数并将它们添加到 Java 对象中,然后 DAO 将数据添加到数据库中.但是,当我在输入后点击添加"按钮时,Web 应用程序根本找不到 servlet.它只是跳过"ajax 函数并继续.所以这是执行插入的 servlet:

I'm learning Java servlets and I wrote two separate servlets for "GET" and "POST". When a "GET" request is sent to the server, the servlet accesses the database and retrieves everything and converts the result to the format that can be recognized by Google Charts. And when a "POST" request is sent to the server, the servlet gets the parameters and adds them to a Java object and then the DAO adds the data to the database. However, when I hit the "add" button after the input, the web app cannot find the servlet at all. It simply just "skips" the ajax function and proceeds. So here's the servlet that does the insertion:

@WebServlet("/InsertServlet")
public class InsertServlet extends HttpServlet 
{
    private static final long serialVersionUID = 1L;
    private EmployeeDao dao;

    public InsertServlet() throws SQLException 
    {
        super();
        dao = new EmployeeDao();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException 
    {
        System.out.println("doPost");
        Employee e = new Employee();
        e.setName(request.getParameter("name"));
        e.setSSN(request.getParameter("ssn"));
        e.setDob(request.getParameter("birth"));
        e.setIncome(request.getParameter("xxxx"));

        dao.addEmployee(e);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<h2>Data Entry Added</h2><br>");
        out.println("<h2>"+request.getParameter("name")+"</h2>");
        out.println("<h2>"+request.getParameter("ssn")+"</h2>");
        out.println("<h2>"+request.getParameter("birth")+"</h2>");
        out.println("<h2>"+request.getParameter("xxxx")+"</h2>");
        out.flush();
        out.close();


    }
}

这里是 index.html:

And here's the index.html:

<form id="inputForm">
<table style="width:80%;border:3px;">
    <tr>
        <td align="center"><input type="text" name="name" id="name" placeholder="First Last"></td>
        <td align="center"><input type="text" name="ssn" id="ssn" placeholder="111111111"></td>
        <td align="center"><input type="text" name="birth" id="birth" placeholder="MM/DD/YYYY"></td>
        <td align="center"><input type="text" name="xxxx" id="xxxx" placeholder="12345"></td>
        <td align="center"><button type="button" name="add" id="add" >Add</button></td>
        <td align="center"><button type="button" name="delete" id="delete">Delete</button></td>
    </tr>
</table>
</form>
$("#add").click(function() {
            var nameIn = $('#name').val();
            var ssnIn = $('#ssn').val();
            var birthIn = $('#birth').val();
            var xxxxIn = $('#xxxx').val();
            if (validate(nameIn, ssnIn, birthIn, xxxxIn) === true) {
                xxxxIn = "$" + xxxxIn;
                var ssn1 = ssnIn.substring(0, 3);
                var ssn2 = ssnIn.substring(3, 5);
                var ssn3 = ssnIn.substring(5);
                ssnIn = ssn1 + '-' + ssn2 + '-' + ssn3;

                $.post("InsertServlet", $("#inputForm").serialize(), function(responseHtml) {
                    $('#state').html(responseHtml);
                });
                window.setTimeout(redraw, 1000);
                redraw();
            }
        });

编辑 1:所以网络应用程序一直工作到add"的 $ajax 发送正确请求的地步.JS 函数运行良好.请求具有与属性对应的正确值.但是,在调用/InsertServlet URL 时,Web 应用程序似乎只是忽略了 servlet,并且在 doPost 方法中 getParameter 方法都返回 null.

Edit 1: So the web app works all the way to the point where the $ajax of "add" sends the proper request. The JS functions worked fine. The request has the correct values corresponding to the attributes. However, when invoking the /InsertServlet URL, it seems that the web app just ignores the servlet and the getParameter methods all return null in the doPost method.

编辑 2:Tomcat 版本:7.0.61.JDK 版本:1.7.0_45.Servlet 版本:3.0

Edit 2: Tomcat version: 7.0.61. JDK version: 1.7.0_45. Servlet version: 3.0

推荐答案

你的错误在于 $.ajax()<的 dataTypedata 属性/code> 选项:

Your mistake is in the dataType and data properties of $.ajax() option:

  $.ajax({
        type:"POST",
        url:"InsertServlet",
        dataType:"json",
        data: {
            name: nameIn, 
            ssn: ssnIn, 
            birth: birthIn, 
            xxxx: xxxxIn
        },
        // ...

根据 $.ajax() 文档dataType 属性指示 jQuery 以什么格式返回 response(在您的情况下,这只是 HTML,如 text/html 并且绝对不是 application/json 所指示的 JSON).它不代表您错误预期的请求参数格式.而且,data 属性必须表示 URL 编码的 HTTP 请求查询字符串符合 application/x-www-form-urlencoded 内容类型,因此不是 JSON 对象.

As per the $.ajax() documentation, the dataType property instructs jQuery in what format the response will be returned (which is in your case by the way just HTML as indicated by text/html and definitely not JSON as indicated by application/json). It does not represent the format of request parameters as you incorrectly expected. And, the data property must represent the URL-encoded HTTP request query string conform the application/x-www-form-urlencoded content type, and thus not a JSON object.

这就解释了为什么请求参数是null.

That explains why the request parameters are null.

删除 dataType 属性.您在这里不需要它,jQuery 足够聪明,可以根据响应的 Content-Type 标头自动检测它.

Remove the dataType attribute. You don't need it here and jQuery is smart enough to autodetect it based on response's Content-Type header.

data 属性修正为真正的 URL 编码的 HTTP 请求查询字符串.您可以通过以下任一方式进行操作:

Fix the data attribute to be a true URL-encoded HTTP request query string. You can do it either of the following ways:

  1. 在表单上使用$.serialize().给定一个

    :
data: $("#yourFormId").serialize(),

  • 使用 $.param() onJSON 对象:

  • Use $.param() on the JSON object:

    data: $.param({
            name: nameIn, 
            ssn: ssnIn, 
            birth: birthIn, 
            xxxx: xxxxIn
        }),
    

  • 手动编写 URL 编码的 HTTP 请求查询字符串.

  • Manually compose the URL-encoded HTTP request query string.

    data: "name=" + encodeURIComponent(nameIn) 
       + "&ssn=" + encodeURIComponent(ssnIn)
       + "&birth=" + encodeURIComponent(birthIn)
       + "&xxxx=" + encodeURIComponent(xxxxIn),
    

  • 使用 JSON.stringify() 以及适当的内容类型.

  • Use JSON.stringify() along with proper content type.

    contentType: "application/json",
    data: JSON.stringify({
            name: nameIn, 
            ssn: ssnIn, 
            birth: birthIn, 
            xxxx: xxxxIn
        }),
    

    这只需要在 servlet 中进行更改:它必须将请求正文解析为 JSON,而不是使用 getParameter() 等.由于这很乏味,您最好将 servlet 替换为 JAX-RS 网络服务,该服务提供内置工具来透明地处理此问题.

    This only requires a change in the servlet: it must parse the request body as JSON and not use getParameter() and such. As this is tedious, you'd better replace the servlet by a JAX-RS webservice which offers builtin facilities to handle this transparently.

    <小时>

    与具体问题无关,使用$.post() 而不是 $.ajax() 减少了样板代码.


    Unrelated to the concrete problem, using $.post() instead of $.ajax() reduces the boilerplate code.

    $.post("InsertServlet", $("#yourFormId").serialize(), function(responseHtml) {
        $('#state').html(responseHtml); 
    });
    

    另见:

    • 如何使用 Servlet 和 Ajax?
    • 这篇关于request.getParameter() 在使用 $.ajax 和 JSON 对象作为数据时返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆