开发者

Collection Post From JSP To Servlet

开发者 https://www.devze.com 2023-03-10 14:38 出处:网络
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 amo

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号