Soumya
Soumya

Reputation: 5412

Passing a variable from one servlet to another servlet

How do I pass a variable array from one servlet to another servlet?

Upvotes: 2

Views: 10258

Answers (1)

BalusC
BalusC

Reputation: 1108632

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

Upvotes: 6

Related Questions