代码之家  ›  专栏  ›  技术社区  ›  kristheman

要求循环内的setAttribute

  •  0
  • kristheman  · 技术社区  · 6 年前

    我在j2EE项目中有一个servlet,我正在为一个硬木项目计算一些材料。我有一个ArrayList,在其中添加所需的必要数量的材料。我想将ArrayList设置为Request属性,以便最终可以在jsp页面上显示它们。

      String execute(HttpServletRequest request, HttpServletResponse response) throws LoginSampleException {
    
      //here is going to a mehtod to acces to database and get the information
    
        ArrayList<Tree> trees = new ArrayList<>();
        for(Tree tree: trees){
             int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
             ArrayList <Integer> amountMaterials = new ArrayList<>();
             amountMaterials.add(amount);
             request.setAttribute("amountMaterials", amountMaterials);
        }
    
    return null; // here I'm eventually going to redirect to my jsp-page
    }
    

    我应该提出请求吗。setAttribute在循环之外还是无关紧要

    这是另一个版本

      ArrayList<Integer> amountMaterials = null; 
    
        ArrayList<Tree> trees = new ArrayList<>();
        for(Tree tree: trees){
             int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
             amountMaterials.add(amount);
    
        }
        request.setAttribute("amountMaterials", amountMaterials);
    
    return null; 
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Srinu Chinka    6 年前

    请参见以下说明:

    第一版:

    ArrayList<Tree> trees = new ArrayList<>();
    for(Tree tree: trees) {
         int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
         ArrayList <Integer> amountMaterials = new ArrayList<>();
         amountMaterials.add(amount);
         request.setAttribute("amountMaterials", amountMaterials);
    }
    
    1. 在此代码版本中,您试图创建新的 ArrayList 每次,如果你有更多 Tree 将创建多个ArrayList对象的对象。

    2. request.setAttribute() 如果将此代码放在具有相同属性名称的循环中 amountMaterials 以前的值将被新值覆盖,最后只有一个值,即最后计算的值。

    所以不建议使用第一个版本。

    第二版:

    ArrayList<Integer> amountMaterials = null; 
    
    ArrayList<Tree> trees = new ArrayList<>();
    for(Tree tree: trees){
         int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
         amountMaterials.add(amount);
    
    }
    request.setAttribute("amountMaterials", amountMaterials);
    

    在这里,您将在循环之外创建ArrayList对象,因此它将只创建一个实例,并且它将具有所有值和 要求setAttribute() 在循环之外,这意味着不会覆盖以前的值。

    通过这个解释,您现在知道要使用哪个版本;)。