0

I'm sending a POST request using jQuery:

$.post(
'test',
{ foo: 'bar'}
);

And I have a simple servlet for processing it:

@WebServlet("/test")
public class TestServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      Map<String, String[]> parameterMap = req.getParameterMap();
  }

}

But the requestMap in the servlet turns out to be empty. What am I doing wrong?

Edit: Forgot to mention that I call this script from the JSF Facelet page. Don't ask me why I bother manually issuing Ajax requests, and why I use servlets to process them. It's a long story. I know it's not a JSF'ish way.

After @BalusC answer, I tried adding a servlet filter like this:

@WebFilter(urlPatterns="/test")
public class TestFilter implements Filter {
    @Override
    public void destroy() { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
}

And it worked! Not only I was able to get the parameters in the filter, but also they were accessible in the servlet! So, can somebody explain me what sort of magic is this?

jFrenetic
  • 5,384
  • 5
  • 42
  • 67
  • What do you see with `firebug`? – gdoron Apr 15 '12 at 11:57
  • I see that it's actually sending a POST request. At the same time I set the breakpoint in Eclipse, and I really catch this request, but without any parameters... I use Chrome Developer Tools, and it shows that the request is actually posted with all the required parameters. – jFrenetic Apr 15 '12 at 12:00

1 Answers1

0

The parameter map will be empty if some code in the request-response chain has invoked request.getReader() or request.getInputStream() beforehand. The HTTP request body can be read and parsed only once (the client ain't going to resend it multiple times on server's needs). Check all your filters.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I have no custom filters. I get a response from Facebook with access token, and I execute this script on page load to pass it to the Servlet. One note however: this script is invoked from JSF Facelet. – jFrenetic Apr 15 '12 at 13:17
  • If `getReader()` or `getInputStream()` is called *before* `getParameter()`, `getParameterMap()`, etc, then the params will remain `null`. From the other way round, if you call `getParameter()`, etc, *before* the `getReader()` or `getInputStream()`, then they will return EOF. Debug your code to check if you aren't calling either of them (in)directly. That's all I can tell based on the symptoms. – BalusC Apr 15 '12 at 22:52