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.

1
  • Your title says getP(data), whereas your code says getP(type). What is the actual problem? Commented Oct 17, 2013 at 16:10

2 Answers 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.

Sign up to request clarification or add additional context in comments.

4 Comments

oh okay. please elaborate more. please. :)
@pepsi Elaborate on what subject? There are keywords in my answer that will help you find what you want.
Thanks man, appreciated your time. just asking about a sample code. since I am very new to java.:)
I fixed this using the contentType: "application/x-www-form-urlencoded", then just get it on the server side using the getParameterMap() method and just manipulate the string to make it a valid json data. :)
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.

1 Comment

Jackson has made me bang my head against the wall for 8 hours, because the error handling is terrible at best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.