Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

jquery - request.getParameter() returns null when using $.ajax with JSON object as data

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


    }
}

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
        },
        // ...

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.

That explains why the request parameters are null.

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.

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

  1. Use $.serialize() on the form. Given a <form id="yourFormId">:

    data: $("#yourFormId").serialize(),
    
  2. Use $.param() on the JSON object:

    data: $.param({
            name: nameIn, 
            ssn: ssnIn, 
            birth: birthIn, 
            xxxx: xxxxIn
        }),
    
  3. Manually compose the URL-encoded HTTP request query string.

    data: "name=" + encodeURIComponent(nameIn) 
       + "&ssn=" + encodeURIComponent(ssnIn)
       + "&birth=" + encodeURIComponent(birthIn)
       + "&xxxx=" + encodeURIComponent(xxxxIn),
    
  4. Use JSON.stringify() along with proper content type.

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

    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.


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

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

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...