2012-01-27 130 views
0

我應該怎麼做?實例化對象的多個實例併發送給jsp

我有一個表單可以發送相同參數的1-5個值:例如,我可以讓用戶填寫3個文本框,每個文本框包含他們喜歡的顏色。我會從使用中獲取這些值:

String [] color = request.getParameterValues("color"); 

這會給我一個這些值的數組。然後,我的計劃是做這樣的事情:

for(int i= 0; i<color.length; i++) 
    { 
     Child child = new Child(color[i]); 
     request.setAttribute("color",color); 

    } 

首先將這個創建一個名爲「色」三個不同的屬性或將這種覆蓋「色」每次屬性?

其次,我如何在最後一頁收集這些信息?

<% Color color =(Color) request.getAttribute("color"); %> 

這會返回只有一個值或我創建的對象數組?

回答

0

首先,這會創建三個單獨的屬性,名爲「color」或 這是否會每次都覆蓋「color」屬性?

setAttribute將覆蓋屬性「color」,並且您將只有最後一個變量可用。但你可以這麼做:

Child [] childs = new Child [color.length]; 
for(int i= 0; i<color.length; i++) { 
    Child child = new Child(color[i]); 
    childs[i] = child; 
} 
request.setAttribute("colors",childs); 

所以在JSP可以retreive顏色如下:

<% Child[] childs =(Child[]) request.getAttribute("colors"); %> 
+0

感謝,但我會如何訪問對象的屬性一旦我在jsp歸因要求? – user975044 2012-01-27 00:51:31

+0

沒關係,我知道它childs [i] .get() – user975044 2012-01-27 00:56:45

+0

你可以使用一個循環和訪問通過childs [i] .getSomeAttr(),如果你的向量的長度是固定的,你可以直接通過索引childs [ 2] .getSomeAttr() – 2012-01-27 00:57:05