【问题标题】:request.setAttribute inside a loop循环内的 request.setAttribute
【发布时间】:2018-05-06 11:15:05
【问题描述】:

我的 j2EE 项目中有一个 servlet,我正在为硬木项目计算一些材料。我有一个 ArrayList,我在其中添加了所需的必要数量的材料。我想将 ArrayList 设置为 reqeust 属性,以便最终可以在 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
}

我应该将 request.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; 
}

【问题讨论】:

    标签: jsp servlets jakarta-ee


    【解决方案1】:

    请看下面的解释:

    第一版:

    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 对象,因此它将仅创建一个实例并且它将具有所有值,并且request.setAttribute() 在循环之外,这意味着您之前的值不会被覆盖。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2014-06-18
      相关资源
      最近更新 更多