Passing a variable from one servlet to another servlet

前端 未结 1 1028
悲&欢浪女
悲&欢浪女 2021-01-07 05:36

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

相关标签:
1条回答
  • 2021-01-07 06:30

    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 讨论(0)
提交回复
热议问题