开发者

Passing a variable from one servlet to another servlet

How开发者_StackOverflow do I pass a variable array from one servlet to another servlet?


If you're passing the current request to another servlet, then just set it as request attribute.

request.setAttribute("array", array);
request.getRequestDispatcher("/servleturl").include(request, response);

It'll be available in another servlet as follows:

Object[] array = (Object[]) request.getAttribute("array");

Or, if you're firing a brand new request to another servlet, then just set it as request parameters.

StringBuilder queryString = new StringBuilder();
for (Object item : array) {
    queryString.append("array=").append(URLEncoder.encode(item, "UTF-8")).append("&");
}
response.sendRedirect("/servleturl?" + queryString);

It'll be available in another servlet as follows:

String[] array = request.getParameterValues("array");

Or, if the data is too large to be passed as request parameters (safe max length is 255 ASCII characters), then just store it in session and pass some unique key as parameter isntead.

String arrayID = UUID.randomUUID().toString();
request.getSession().setAttribute(arrayID, array);
response.sendRedirect("/servleturl?arrayID=" + arrayID);

It'll be available in another servlet as follows:

String arrayID = request.getParameter("arrayID");
Object[] array = (Object[]) request.getSession().getAttribute(arrayID);
request.getSession().removeAttribute(arrayID);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜