如何向 Java Servlet 的现有 HttpServletRequest 添加参数?

发布于 2024-12-22 06:30:38 字数 323 浏览 0 评论 0原文

我想向我的 HttpServletRequest 的参数映射添加一个新参数。

以下代码

 request().getParameterMap().put("j_username", user);
 request().getParameterMap().put("j_password", pwd);

会产生此错误

no modifications are allowed to a locked parameter map

执行此操作的正确方法是什么?

I want to add a new parameter to the parameter map of my HttpServletRequest.

The following code

 request().getParameterMap().put("j_username", user);
 request().getParameterMap().put("j_password", pwd);

creates this error

no modifications are allowed to a locked parameter map

What is the correct way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下凄凉 2024-12-29 06:30:39

请求的参数是浏览器作为参数发送的值。没有理由改变它们。如果要将某个值与请求关联,请使用属性而不是参数。这还有一个额外的优点,即属性可以是任何对象而不仅仅是字符串:

request.setAttribute("user", new User(userName, password));

如果将请求转发到另一个资源,您可以添加参数(尽管我不会说这是一个好的做法):

request.getRequestDispatcher("/some/path?j_username=" + user + "&j_password=" + pwd).forward(request, response);

参数应该正确编码,尽管。

The parameters of a request are the values sent as parameters by the browser. There is no reason to change them. If you want to associate some value to the request, use an attribute rather than a parameter. This has the additional advantage that an attribute may be any object and not just a String:

request.setAttribute("user", new User(userName, password));

You may add parameters if you forward the request to another resource (although I wouldn't say it's a good practice):

request.getRequestDispatcher("/some/path?j_username=" + user + "&j_password=" + pwd).forward(request, response);

The parameters should be encoded correctly, though.

娇柔作态 2024-12-29 06:30:39

我遇到了类似的问题,并通过制作参数映射的副本来解决它。

Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());

I ran into a similar issue and got around it by making a copy of the parameter map.

Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文