Passing a variable from one servlet to another servlet

被刻印的时光 ゝ 提交于 2019-12-19 04:13:10

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/4221825/passing-a-variable-from-one-servlet-to-another-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!