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);
精彩评论