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

查看:86
本文介绍了将$ .ajax和JSON对象用作数据时,request.getParameter()返回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();
            }
        });

因此,Web应用程序一直运行到添加"的$ ajax发送适当请求的地步. JS函数运行良好.该请求具有与属性相对应的正确值.但是,当调用/InsertServlet URL时,Web应用程序似乎只是忽略了servlet,而getParameter方法在doPost方法中都返回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.

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属性:

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 响应将以哪种格式返回(在您的情况下,这只是text/html指示的HTML,而绝对不是application/json指示的JSON).它不代表您错误预期的请求参数格式.并且,data属性必须表示符合application/x-www-form-urlencoded内容类型的URL编码的HTTP请求查询字符串,因此不能是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() .给定<form id="yourFormId">:

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

  • 在JSON对象上使用 $.param() :

  • 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()等.由于这很麻烦,因此最好用JAX-RS Web服务替换Servlet,该Web服务提供内置的工具来透明地处理此问题.

    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?
    • See also:

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

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