为什么HttpServletRequest中的getAttribute()用于GET方法但不适用于POST方法? [英] Why does getAttribute() in HttpServletRequest works for GET method but not for POST method?

查看:659
本文介绍了为什么HttpServletRequest中的getAttribute()用于GET方法但不适用于POST方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试向servlet发出请求的客户端AJAX问题。但是这个错误发生在服务器端。您可以参考我的原始问题此处。从与更有经验的人的讨论中,我发现servlet使用request.getAttribute()方法从请求中检索参数,而不是getParameter()。所以我想打开一个新的问题来澄清我的疑问。现在我的问题是:如果我使用GET方法从客户端传递参数到服务器,getAttribute()in Servlet工作正常,我可以得到参数值。但是当我使用POST方法时,getAttribute()返回null。为什么它适用于GET而不适用于POST?

解决方案

当属性来自GET或POST方法时,您应该始终使用getParameter。并且当请求从另一个servlet / jsp转发时使用getAttribute。如:

  ServletA:
request.setAttribute(test,value)
请求.getRequestDispatcher(/ ServletB)。forward(request,response)


ServletB:
request.getAttribute(test)< - 你可以得到test属性通过使用getAttribute


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?

解决方案

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

这篇关于为什么HttpServletRequest中的getAttribute()用于GET方法但不适用于POST方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆