【问题标题】:Create an ArrayList on a Servlet在 Servlet 上创建 ArrayList
【发布时间】:2015-04-03 01:23:02
【问题描述】:

我在 Servlet 上创建列表时遇到问题。我有以下代码:

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    List lIngredients = new ArrayList<>();
    String ingrediente = request.getParameter("Ingredientes");
    String action = request.getParameter("action"); //elegimos a qué pantalla pasar en función de la acción que nos llegue de la interfaz

    if ("Buscar todas las recetas".equalsIgnoreCase(action)) {
        request.setAttribute("AllReceipes", RecetaDao.getAllReceipes());
        request.getRequestDispatcher("receipes.jsp").forward(request, response);
    }else if ("Buscar por ingredientes".equalsIgnoreCase(action)){
              lIngredients.add(ingrediente);
              request.setAttribute("AllIngredients", RecetaDao.getSomeReceipes(lIngredients));
              request.getRequestDispatcher("perIngredient.jsp").forward(request, response);
    }else if ("Agregar ingrediente".equalsIgnoreCase(action)){
             lIngredients.add(ingrediente);
    }
    }

问题是我一直保存相同的值。我不知道是否可以重置我制作的“ingrediente”和“action”字符串,并让用户从 JSP 中选择其他值。

谢谢。

这是 JSP:

`<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <form action="./optionServlet" method="POST">     
    <table border="1">
        <form action="demo_form.asp" autocomplete="on">     
        <th><FONT FACE="Times New Roman" SIZE=3> Ingredientes: </th>
        <td><input type="text" name="Ingredientes" value="${Receta.Ingredientes}" list="datalist1" /></td>
        <datalist id="datalist1">
             <option value="Aceite"><option value="AceiteOliva"> <option value="AceitunasNegras"><option value="Ajo"><option value="Albahaca">
             <option value="AlbahacaFresca"><option value="Azucar"><option value="CarnePicada"><option value="Cebolla"><option value="CebollaMorada">
             <option value="Croutons"><option value="DienteDeAjo"><option value="Espinaca"><option value="FileteSalmon"><option value="Guisantes">
             <option value="Harina"><option value="Huevo"><option value="LaminaParaCanelones"><option value="Lechuga"><option value="Macarrones">
             <option value="Mantequilla"><option value="MasaPizza"><option value="Miel"><option value="Mostaza"><option value="Oregano">
             <option value="PanRallado"><option value="Patata"><option value="PechugaPollo"><option value="Pepino"><option value="Perejil"><option value="Pimienta">
             <option value="PimientoRojo"><option value="QuesoFeta"><option value="QuesoMozzarella"><option value="QuesoParmesano"><option value="QuesoRicota">
             <option value="Sal"><option value="SalsaQueso"><option value="Tomate"><option value="TomateTriturado"><option value="Zanahoria">
        </datalist>
        <button><input type="submit" name="action" value="Buscar todas las recetas" /></button>
        <button><input type="submit" name="action" value="Buscar por ingredientes" /></button>
        <button><input type="submit" name="action" value="Agregar ingrediente" /></button>
        <table>
            <tr>
                <td> <font color="#74DF00"><b><c:out value="${mensajesOK}"/></b></font> </td>`

这是正确的代码:

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    List lIngredients = (List) session.getAttribute("Ingredientes");
    response.setContentType("text/html;charset=UTF-8");
    if (lIngredients == null) {
       lIngredients = new ArrayList<>();
       session.setAttribute("Ingredientes", lIngredients);
    }
    String ingrediente = request.getParameter("Ingredientes");
    String action = request.getParameter("action"); //elegimos a qué pantalla pasar en función de la acción que nos llegue de la interfaz

    if ("Buscar todas las recetas".equalsIgnoreCase(action)) {
        request.setAttribute("AllReceipes", RecetaDao.getAllReceipes());
        request.getRequestDispatcher("receipes.jsp").forward(request, response);
    }else if ("Buscar por ingredientes".equalsIgnoreCase(action)){
              lIngredients.add(ingrediente);
              request.setAttribute("AllIngredients", RecetaDao.getSomeReceipes(lIngredients));
              request.getRequestDispatcher("perIngredient.jsp").forward(request, response);
    }else if ("Agregar ingrediente".equalsIgnoreCase(action)){
             lIngredients.add(ingrediente);
             request.getRequestDispatcher("option.jsp").forward(request, response);
             ingrediente = request.getParameter("Ingredientes");
             action = request.getParameter("action");
    }
}

【问题讨论】:

  • “我一直保存相同的值” - 你能解释一下你的意思吗?
  • 我有一个 jsp 页面,其中有一个成分列表。我想一直选择一个不同的,而不是一旦我有一些关于“ingrediente”参数的信息,我就不能选择一个新的,这就是为什么我一直保存我在第一个写的相同成分时间
  • 我对外国(西班牙语?)文本有点困惑,但你的意思是while("Buscar por ingredientes".equalsIgnoreCase(action))(不是!)吗?
  • 成分:成分; Buscar todas las recetas:查找所有收据; Buscar por 成分:寻找成分; Agregar成分:添加成分。虽然用户没有按下该按钮,但它应该继续询问。我想过清除按钮和参数的信息吗? (对不起西班牙人!)
  • 你为什么要循环播放?如果动作以“Agregar Ingrediente”的形式出现,则循环将变得不确定。

标签: java jsp servlets arraylist


【解决方案1】:

问题是您在每次请求时都创建了一个新的List

List lIngredients = new ArrayList<>();

因为它是一个局部变量,一旦请求完成,它就不再存在。因此,当用户最终决定搜索食谱时,您可以使用之前的值,您需要将成分 List 持久化到会话中。

HttpSession session = request.getSession();
List lIngredients = (List) session.getAttribute("Ingredientes");

if (lIngredients == null) {
    List lIngredients = new ArrayList<>();
    session.setAttribute("Ingredientes", lIngredientes);
}

【讨论】:

  • 请注意,您还需要将列表放入session。否则,session.getAttribute() 将始终返回 null。我错过了,现在已经在我的答案中更新了。
猜你喜欢
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 2017-09-23
  • 2012-03-21
  • 2011-06-04
  • 2014-07-21
相关资源
最近更新 更多