4

I search this topic on web but I can't get a example that worked. I will be gladed with someone could give me a help.

this is what I testing.

 $.ajax({
    url: 'GetJson',
    type: 'POST',        
    dataType: 'json',
    contentType: 'application/json',

    data: {id: 'idTest'},
    success: function(data) {
        console.log(data);
    }
});

in Sevlet

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String id = request.getParameter("id");
    String id2[] = request.getParameterValues("id");        
    String id3 = request.getHeader("id");

}

I'm getting null in everything.

gae
  • 77
  • 1
  • 2
  • 7
  • That question talk about how to get parameters from servlet to webpage but dont have the opposite. – gae Oct 16 '13 at 06:58

2 Answers2

10

I had the same issue with getParameter("foo") returning null in the servlet. Found a simple solution which might be useful to people here. Use the default value

contentType='application/x-www-form-urlencoded; charset=UTF-8'

or leave it out. This will automatically encode the request with the data in parameters.

Hope this helps...

Aviral
  • 1,141
  • 1
  • 10
  • 16
5

The sort answer is that this data is hidden in the request InputStream.

The following servlet is a demo of how you can use this (I am running it on a JBoss 7.1.1):

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="fooServlet", urlPatterns="/foo")
public class FooServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = req.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buf = new byte[32];
        int r=0;
        while( r >= 0 ) {
            r = is.read(buf);
            if( r >= 0 ) os.write(buf, 0, r);
        }
        String s = new String(os.toByteArray(), "UTF-8");
        String decoded = URLDecoder.decode(s, "UTF-8");
        System.err.println(">>>>>>>>>>>>> DECODED: " + decoded);

        System.err.println("================================");

        Enumeration<String> e = req.getParameterNames();
        while( e.hasMoreElements() ) {
            String ss = (String) e.nextElement();
            System.err.println("    >>>>>>>>> " + ss);
        }

        System.err.println("================================");

        Map<String,String> map = makeQueryMap(s);
        System.err.println(map);
        //////////////////////////////////////////////////////////////////
        //// HERE YOU CAN DO map.get("id") AND THE SENT VALUE WILL BE ////
        //// RETURNED AS EXPECTED WITH request.getParameter("id")     ////
        //////////////////////////////////////////////////////////////////

        System.err.println("================================");

        resp.setContentType("application/json; charset=UTF-8");
        resp.getWriter().println("{'result':true}");
    }

    // Based on code from: http://www.coderanch.com/t/383310/java/java/parse-url-query-string-parameter
    private static Map<String, String> makeQueryMap(String query) throws UnsupportedEncodingException {
        String[] params = query.split("&");
        Map<String, String> map = new HashMap<String, String>();
        for( String param : params ) {
            String[] split = param.split("=");
            map.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
        }
        return map;
    }
}

With the request:

$.post("foo",{id:5,name:"Nikos",address:{city:"Athens"}})

The output is:

>>>>>>>>>>>>> DECODED: id=5&name=Nikos&address[city]=Athens
================================
================================
{address[city]=Athens, id=5, name=Nikos}
================================

(NOTE: req.getParameterNames() does not work. The map printed in the 4th line contains all the data normally accessible using request.getParameter(). Note also the nested object notation, {address:{city:"Athens"}}address[city]=Athens)


Slightly unrelated to your question, but for the sake of completeness:

If you want to use a server-side JSON parser, you should use JSON.stringify for the data:

$.post("foo",JSON.stringify({id:5,name:"Nikos",address:{city:"Athens"}}))

In my opinion the best way to communicate JSON with the server is using JAX-RS (or the Spring equivalent). It is dead simple on modern servers and solves these problems.

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
  • thank you. With this I could do what I need. – gae Oct 16 '13 at 07:00
  • whats the difference between gae using $.ajax and you using $.post? – Vnge Dec 04 '13 at 18:16
  • 1
    More compact syntax for the example. – Nikos Paraskevopoulos Dec 04 '13 at 18:24
  • 2
    Terrible advice. User is just doing it completely wrong in jQuery. The problem should be **solved** in jQuery side, not be **workarounded** in Servlet side. OP should just have sent the data as a real JSON object with key-value pairs, not as a string in JSON format. With the proper content type set (the default one), jQuery will automatically deal with it and this way the request.getParameterXxx() will transparently continue working. – BalusC Dec 17 '15 at 08:30
  • @BalusC , if the user is doing it wrong on the ajax side (which is probably right) then could you provide the correct way to do this in ajax? iam having the same problem, i've been looking everywhere, i tried like 100 things – aero May 30 '17 at 06:30