【问题标题】:display the content of arraylist (java class method) in mvc spring application在mvc spring应用中显示arraylist(java类方法)的内容
【发布时间】:2017-03-22 14:05:15
【问题描述】:

该方法的输出是一个字符串数组列表(包含方法 displayPrice 的类 testh 已经使用 Eclipse 工作)

package classe_j;
public class testh {
public static ArrayList<String> displayPrice(String inputFileName, String categorie) {

return priceP; 
} }

现在我想在表格中显示 ArrayList 的内容,如下所示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="classe_j.*"%>
..........
<th><%=testh.displayPrice() %></th>

但我没有出错,但运行时我得到了SystemError
有没有更好的方法来做到这一点 先感谢您

【问题讨论】:

    标签: java spring-mvc jakarta-ee spring-tool-suite


    【解决方案1】:

    第 1 步:将列表添加到 Spring model map 作为属性

    modelMap.addAttribute("prices", testh.displayPrice("file", "category"));

    第二步:需要使用JSTLcore标签

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <table>
       <tr>
          <th>Col1</th>
          <th>Col2</th>
          <!-- rest of you columns -->
       </tr>
    
      <c:forEach items="${prices}" var="list">
         <tr>
             <td>${list.commodity}</td>
             <td>${list.old_price} - ${list.new_price}</td> // you can add values in one column
             <!-- rest of you columns data-->
         </tr>
       </c:forEach>
    
     </table> 
    

    【讨论】:

    • 谢谢,但我没有使用 Controller,testh 是一个包含 displayPrice 方法的 java 类,它返回了一个我想在 c:foreach 中使用它的 ArrayList
    • 你没有展示你的程序的流程。本质是需要将带有价格的数组列表添加到请求参数中,以便JSTL核心标签可以解析它。如果你使用 Spring-MVC,你通常通过 ModelMap 机制来完成。
    【解决方案2】:

    我建议使用 JSTL 库来迭代和循环列表而不是 scriplet。

    确保您的列表在页面、请求、会话和应用程序属性中可用,然后使用以下代码 sn-p 在您的 jsp 中打印。

    使用 JSTL

    <c:forEach items="${list}" var="item">
        ${item}<br>
    </c:forEach>
    

    但如果你还想继续使用 scriplet,这里是你的选择。

    选项 1:在您的列表上循环(for 循环)

    选项 2:在列表上使用迭代器(while 循环)

    这是选项 1 的实现。

    带脚本(不推荐);

    <% 
    List<String> list = testh.displayPrice();
    for (int i=0;i<list.size();i++)
              {
    
                  out.println(list.get(i));
    
              } %>
    

    【讨论】:

    • 谢谢,我已经尝试过使用c:foreach,但问题是输出在另一个类java中(其中包含java类(testh),所以我得到了使用脚本的方法然后我使用c:foreach 进行迭代,但它没有用,请注意 displayPrice 的输出是一个 ArrayList 我需要的只是将其输出存储到 arrayList 然后使用 JSTL 迭代任何建议谢谢
    • 你的意思是“输出在另一个类java中,你是说testh是一个内部类
    • testh 是 java 类,它在 Eclipse IDE 中运行良好,但我需要在这个 java web 应用程序中使用它,我稍微清楚了一点
    • 您的应用程序中是否使用了任何 Servlet?
    • 我在回答中提到的唯一使用 jstl 库的方法是确保您在页面/请求/应用程序范围内设置/添加列表或您想要在 jsp 中引用的任何对象...就是这样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2018-01-18
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2021-04-11
    相关资源
    最近更新 更多