how to get value from request attribute outside loop

Tani :

I am trying to set values in request object inside for loop and it has been set successfully but How can I get the value if value is set inside the loop. Code which I have tried is given below-

        String str = "";                
            for(int i=0; i<sizearray.length; i++){
                str += sizearray[i];                         
                request.setAttribute("ssize", str.substring(str.lastIndexOf("-") + 1));       // two value set ie. 11 and 19
            }               
        out.println(request.getAttribute("ssize"));  // giving one value ie. 19
Yogesh Badke :

This is because you are overriding older values with newer values as you are using the same key for all. A better approach would be to create a Map, put data into it and then store this map into request object as an attribute.

    Map<String, String> dataMap = new HashMap<>();
    String str = "";                
    for(int i=0; i<sizearray.length; i++) {
        str += sizearray[i];                         
        dataMap.put("data"+i, str.substring(str.lastIndexOf("-") + 1));       
    }    
    request.setAttribute("ssize", dataMap);
    out.println(request.getAttribute("ssize")); // this will now give you all values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161157&siteId=1