简体   繁体   English

将类的ArrayList从jsp传递到servlet

[英]Passing an ArrayList of a class from a jsp to a servlet

I have an ArrayList of a class Room. 我有一个类Room的ArrayList。 I need to send it from a jsp to a servlet. 我需要将它从jsp发送到servlet。

It seems the only way an html or a jsp can send values to a servlet is via a form, the method I tried was to pass it as a hidden parameter as follows: 似乎html或jsp可以将值发送到servlet的唯一方法是通过表单,我尝试的方法是将其作为隐藏参数传递,如下所示:

<input type="hidden" name="allRooms" value="<%=request.getAttribute("allRooms") %>" />

But in the servlet to which i submit this form I get a compile error "String cannot be converted to List" for the following: 但是在我提交此表单的servlet中,我收到了一个编译错误“String无法转换为List”,如下所示:

 List<Room> allRooms=(List<Room>)request.getParameter("allRooms");

Just converting the parameter to an Object type first and then converting it to a List as shown below gives the same exception but this time as a Runtime Exception: 只需先将参数转换为Object类型,然后将其转换为List,如下所示,会产生相同的异常,但这次是运行时异常:

 Object a=(Object)request.getParameter("allRooms");
 List<Room> allRooms=(List<Room>)a;

Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ? 是否有任何方法将List传递给servlet,或者我必须将它设置为JSP中的会话变量?

Thanks in advance. 提前致谢。

Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ? 是否有任何方法将List传递给servlet,或者我必须将它设置为JSP中的会话变量?

Use session .That is one best solution. 使用session 。这是一个最好的解决方案。

There is no way to represent an ArrayList in HTML to send via html form. 无法在HTML中表示通过html表单发送的ArrayList Use session instead. 请改用session

I think if you pass the following params, and array is formed in servlet side 我想如果你传递下面的参数,并且数组是在servlet端形成的

param[0]=ss , param[1]=ssw

You could do this. 你可以做到这一点。

List<String> roomParams =(List<String>)request.getParameter("param");

But to make this. 但要做到这一点。

List<Room> allRooms=(List<Room>)request.getParameter("allRooms");

That I think is not possible, so you should use Session attributes 我认为这是不可能的,所以你应该使用Session属性

session.setAttribute("allRooms", new ArrayList<Room>());

I believe you should not be sending the List to Servlet directly and should look out for other options. 我相信你不应该直接将List发送给Servlet ,并应该寻找其他选择。

How are you generating the ArrayList on the browser page? 你是如何在浏览器页面上生成ArrayList的? If it is generated from a multi-select element from UI, then you can access the request parameter values as Array in Servlet . 如果它是从UI中的多选元素生成的,那么您可以在Servlet中将请求参数值作为Array访问。

Shishir Shishir

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM