HttpServletRequest - 设置参数
我知道我可以使用 HttpServletRequest.getParameter() 来获取 URL 参数值。
是否有等效的方法可以设置/替换该值?
I know that I can use HttpServletRequest.getParameter()
to get the URL parameter values.
Is there an equivalent method with which I can set/replace the value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,没有。
您只能更改属性,不能更改参数。
实现类似功能的唯一方法是包装请求(使用为 getParameter 返回其他内容的类)。
相关好奇心:某些 servlet 容器中存在一个错误,可以让您执行
request.getParameterValues(name)[0] = "newValue"
,但这只会导致不一致。No, there is not.
You can only change attributes, not parameters.
The only way to achieve something similar would be to wrap the request (with a class that returns something else for getParameter).
Related curiosity: There is a bug in some servlet containers that would let you do
request.getParameterValues(name)[0] = "newValue"
, but this can only lead to inconsistencies.您可以通过用自定义
HttpServletRequestWrapper
实现替换了位于链早期的Filter
内的参数映射。然而,这听起来像是一种解决方法。在其中一条评论中,您表示想要对参数进行编码(实际上:解码它们,因为它们已经编码)。您正在寻找解决方案的错误方向。对于
GET
请求参数,编码需要在 servletcontainer 本身中设置(例如 Tomcat,只需设置 HTTP 连接器的URIEncoding
属性)。对于POST
,您需要通过ServletRequest#setCharacterEncoding()
。另请参阅这篇文章中的详细解决方案< /a> (阅读整篇文章以了解完整情况)。You can make the parametermap a modifiable map by replacing the
HttpServletRequest
with a customHttpServletRequestWrapper
implementation which replaces the parametermap inside aFilter
which is been placed early in the chain.However, this smells like a workaround. In one of the comments you stated that you wanted to encode the parameters (actually: decode them, because they are already encoded). You're looking in the wrong direction for the solution. For
GET
request parameters the encoding needs set in the servletcontainer itself (in case of for example Tomcat, just setURIEncoding
attribute of the HTTP connector). ForPOST
, you need to set it byServletRequest#setCharacterEncoding()
. Also see the detailed solutions in this article (read the whole article though to understand the complete picture).我认为不存在。但是您可以使用 setAttribute() 方法以类似的方式;您只需使用 getAttribute()(而不是 getParameter())即可稍后获取该值。
I don't think there is. But you can use the setAttribute() method in a similar fashion; you just have to use getAttribute() -- not getParameter() -- to get the value back later.
不。但是,你为什么要这么做呢?可能还有其他方法可以完成您需要做的事情。
No. However, why would you want to do that? There may be other ways of accomplishing what you need to do.
请求参数通过 HTTP 从客户端提交到 servlet 或 JSP。它们不是由服务器端代码设置的,因此不需要任何设置方法 (setParameter())。
此外,它将增加安全性,任何人都无法更改请求参数。
Request parameters are submitted to a servlet or JSP from a client via HTTP. They are not set by server-side code so there is no need for any set methods (setParameter()).
Also, it will add security that no one can change request parameters.