0

On the web page, I use JQuery to send Ajax call to my servlet.

function sendAjax() {
            $.ajax({
                url: "/AddOrUpdateServlet",
                type: 'POST',   
                dataType: 'json',
                data: {"name": "hello world"},
                contentType: 'application/json',
                mimeType: 'application/json',

                success: function (data) {   

                },
                error:function(data,status,er) {
                    alert("error: "+data+" status: "+status+" er:"+er);
                }
            });         
        }   

In the AddOrUpdateServlet's doPost, I have the following code:

protected void doPost(HttpServletRequest request, 
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub 
    String name = request.getParameter("name"); 
    if (name == null) 
        System.out.println("null"); 

    /*
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(new Integer(1).toString());
    response.getWriter().close();
    */

}

I can see the parameter was successfully sent and received by the servlet as the console printed out "null". But why was the servlet unable to get the "name" param?

Naman Gala
  • 4,670
  • 1
  • 21
  • 55
alextc
  • 3,206
  • 10
  • 63
  • 107

1 Answers1

0

Because you have passed the "name" parameter in request body of POST,and more over it is JSON type.

Just make it GET request and remove the below line

`contentType: 'application/json',mimeType: 'application/json',

EDIT:-- write below line of code in your servlet,you will have to use JSON library,to parse the data in your servlet(GSON or Jackson) See :- Stack overflow answer

StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject = JSONObject.fromObject(jb.toString());
  } catch (ParseException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }
Community
  • 1
  • 1
dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • But I still want to use POST instead of GET. How? – alextc Jan 08 '15 at 04:57
  • updated my answer with reference to http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data, in this case you do not have to change your method. – dReAmEr Jan 08 '15 at 05:05
  • Thanks RE350. I think I am nearly there. But the problem is JQuery sent "name=hello+world" instead of the original JSON data {"name": "hello world"}. I think it was automatically transformed. – alextc Jan 08 '15 at 05:19
  • 1
    change the below line data: {"name": "hello world"}, to data: JSON.stringify({"name": "hello world"}), – dReAmEr Jan 08 '15 at 05:21