Why does getAttribute() in HttpServletRequest works for GET method but not for POST method?

有些话、适合烂在心里 提交于 2019-12-12 06:56:36

问题


I'was debugging a client-side AJAX problem that is making request to servlet. But the bug turned out to be at server side. You can refer to my original question here. From the discussion with more experienced people, I found out that servlet is using request.getAttribute() method to retrieve parameters from the request instead of getParameter(). So I thought to open a new question to clear my doubt.

Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?


回答1:


You should always use getParameter, when attribute come from GET or POST method. And use getAttribute when request is forwarded from another servlet/jsp. Such as :

ServletA:
request.setAttribute("test","value")
request.getRequestDispatcher("/ServletB").forward(request, response)


ServletB:
request.getAttribute("test") <-- you can get test attribute by using getAttribute



回答2:


Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?

Complete nonsense. You're apparently working on an existing project which has a lot of other existing servlets and filters. My cents that there's another filter in the request-response chain which maps request parameters to request attribtues for some unobvious reason.

Please create a blank playground project and create a playground servlet to familarize yourself better with servlets without all that noise in existing projects.

See also:

  • Our Servlets wiki page


来源:https://stackoverflow.com/questions/7266338/why-does-getattribute-in-httpservletrequest-works-for-get-method-but-not-for-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!