java - 在 Servlet 上创建 ArrayList

标签 java jsp servlets arraylist

我在 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");
    }
}

最佳答案

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

List lIngredients = new ArrayList<>();

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

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

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

关于java - 在 Servlet 上创建 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305838/

相关文章:

Java Servlet 处理 html post 数据

java - 错误页面返回状态代码 200 默认响应

java - Ajax 登录请求在 jquery 中使用 $.post() 方法不起作用

java - 在 RecylerView 上的 ImageView 上膨胀图像

java - Java 中来自静态上下文的模糊调用

java - net::ERR_INCOMPLETE_CHUNKED_ENCODING 使用 JSP 的 SPRING MVC 应用程序

javascript - 在 JSP 中模态提交后处理表单

Java如何解析带空格的整数

java - 如何在 GUI 文本框而不是 Eclipse 控制台上打印输出?

java - jsp 中跨站脚本编写时出现错误