将列表数据从jsp发送到servlet
我有一个 List
,我想将其作为 GET 查询字符串参数传递给后续请求:
<a href="servlet?list=<%=request.getAttribute("list")%>">link</a>
在 servlet 内,我尝试按如下方式检索它:
String[] list = req.getParameterValues("list");
它不起作用。我怎样才能让它发挥作用?
I have a List
and I want to pass it to the subsequent request as GET query string parameter:
<a href="servlet?list=<%=request.getAttribute("list")%>">link</a>
Inside the servlet I am trying to retrieve it as follows:
String[] list = req.getParameterValues("list");
It does not work. How can I get it to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了能够使用
getParameterValues()
,必须以以下格式发送多个参数:但是
List#toString()
打印以下格式(在浏览器中右键单击页面并选择查看源代码来查看它):这显然行不通。有几种方法可以解决这个问题:
正如 Bozho 所说,打印它以逗号分隔(或保持不变)并使用
request.getParameter()
代替,分割字符串并使用常见的String
方法,例如split()
、substring()
、indexOf()
等只需以预期格式打印即可。最好的方法是为此创建一个 EL 函数。
将其存储在会话中:
这样您就可以在下一个请求中从同一会话中检索它:
如果需要,您可以将密钥作为请求参数传递。
如果您已经在服务器端(应用程序范围、数据库等)中拥有该列表,那么就不要传递该列表。仅传递那些能够提供足够信息以重新加载/重新填充 servlet 中的列表的参数。查询字符串有最大长度限制,最好不超过 255 个 ASCII 字符。如果列表包含超过数百个项目,那么您将面临它们被截断的风险。
In order to be able to use
getParameterValues()
, multiple parameters has to be sent in the format:But the
List#toString()
prints the following format (rightclick page in browser and choose View Source to see it):This is obviously not going to work. There are several ways to solve this problem:
As Bozho said, print it commaseparated (or keep it unchanged) and use
request.getParameter()
instead and split the string and repopulate the list using the usualString
methods likesplit()
,substring()
,indexOf()
, etc.Just print it in the expected format. Nicest would be to create an EL function for that.
Store it in the session:
so that you can just retrieve it from the same session in the next request:
If necessary, you can pass the key as request parameter instead.
If you already have the list in the server side (application scope, database, etc), then just don't pass the list around. Pass only those parameters around which gives enough information to reload/repopulate the list in the servlet. The query string has a limitation in maximum length which should preferably not exceed 255 ASCII characters. If the list contains over some hundred of items, you risk that they will be truncated anyway.
list
属性是一个List
,您不应该依赖它的toString()
,它在您的代码中调用(在幕后) 。相反,您必须迭代列表并在元素之间插入逗号。
the
list
attribute is aList
, and you should not rely on itstoString()
, which is called in your code (behind the scene).Instead, you have to iterate the list and insert commas between the elements.