how to post a collectio开发者_如何学Gon (List of object) to servlet in jsp inside a form?
Thanks.
HTTP/HTML doesn't understand Java objects. You've to convert them to strings when putting them among the HTML and then convert them back when extracting them from the request parameters.
String yourCollectionAsString = getAsString(yourCollection);
request.setAttribute("yourCollectionAsString", yourCollectionAsString);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
with
<input type="hidden" name="yourCollection" value="${yourCollectionAsString}" />
and
String yourCollectionAsString = request.getParameter("yourCollection");
List<SomeObject> yourCollection = getAsObject(yourCollectionAsString);
A JSON parser like Google Gson may be useful here as it serializes and deserializes Java objects into a relatively compact String format in a single line of Java code (which is also reuseable for JavaScript in the client side, for the case that).
Alternatively, you can also store it in the session along with a long, unique, autogenerated ID and pass that ID around instead.
String yourCollectionID = UUID.randomUUID().toString();
request.getSession().setAttribute(yourCollectionID, yourCollection);
request.setAttribute("yourCollectionID", yourCollectionID);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
with
<input type="hidden" name="yourCollectionID" value="${yourCollectionID}" />
and
String yourCollectionID = request.getParameter("yourCollectionID");
List<SomeObject> yourCollection = (List<SomeObject>) request.getSession().getAttribute(yourCollectionID);
request.getSession().removeAttribute(yourCollectionID);
精彩评论