0

I am writing a servlet that will accept POST data coming from an AJAX request.

Here is the code I send from the client:

$.ajax({
            type: "POST",
            url: "urlservlet",
            data: "{type:'" + "country" + 
            "', country:'" + $('#country').val() +
            "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {

            }


And this is the servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
    string test = request.getParameter("type");
}

But the thing is I always get the type equal to null. I don't know why.

Kindly help me.

4

2 回答 2

5

You are writing JSON to your request body and expecting request parameters. From the javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

You haven't posted form data and don't have a query string.

What you want is to read the HTTP request body with HtppServletRequest#getInputStream() and parse the JSON to extract your element.

于 2013-10-17T16:08:39.417 回答
2

The problem is as @Sotirios describes. However, I would solve it by using a Java REST framework on the server side like RESTEasy, Spring MVC, or Restlet. It is preferable to use an abstraction so you can focus on your business logic rather than low-level details of the Servlet API.

And a JSON serializer/deserializer like Jackson to avoid dealing with the low-level details of parsing JSON. Jackson as well as its alternatives integrate seamlessly with the REST frameworks I mentioned.

I like good abstractions.

于 2013-10-17T16:19:06.847 回答