2016-11-18 94 views
0

我需要將兩個數組轉發到一個jsp頁面來顯示它們。我已經成功地使用下面的代碼轉發單個陣列:如何使用sendRedirect從servlet發送多個數組到jsp

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { 

    String n = request.getParameter("name"); 
    int k = Integer.parseInt(n); 
    int array[] = new int[3]; 
    PrintWriter out = response.getWriter(); 
    List<RecommendedItem> recommendations = new ArrayList<RecommendedItem>(); 

    try { 
     recommendations = App.getRecommend(k); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    int i = 0; 
    // out.println("we recommend"); 
    for (RecommendedItem recommendation : recommendations) { 
     // out.println(recommendation.getItemID()+" " 
     // +recommendation.getValue()); 
     array[i] = (int) recommendation.getItemID(); 
     i++; 
    } 

    String param = Arrays.toString(array); 
    param = param.substring(1, param.length() - 1);// removing enclosing [] 
    String encArray = URLEncoder.encode(param, "utf-8"); 

    // Send encArray as parameter. 
    response.sendRedirect(("output.jsp?fib=" + encArray)); 
} 

但現在我要轉發的(int)recommendation.getValue()組成的output.jsp的第二陣列。可以使用response.sendRedirect()完成嗎?

回答

0

可以通過參數發送任何你想要的字符串。在你的情況下,只需添加第二個參數,你重定向你的第二個編碼陣列,像:

response.sendRedirect(("output.jsp?fib=" + encArray + "&fib2=" + encArray2)); 

,並得到它在你fib參數做了同樣的方式。

但是,處理Servlet中值的傳輸的更好和更好的方法是通過RequestDispatcher。代碼爲:

req.setAttribute("fib", encArray); 
req.setAttribute("fib2", encArray2); 
req.getRequestDispatcher("output.jsp").forward(req, response); 

而且使用恢復JSP中的數組:

<% 
    String encArray = (String) request.getAttribute("fib"); 

    // ... 

    String encArray2 = (String) request.getAttribute("fib2"); 
%> 

注:隨着你甚至可以設置和恢復Java數組對象第二個選項(String[] )而不需要對其進行編碼。