在Servlet上创建一个ArrayList

时间:2015-02-03 18:11:00

标签: 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");
    }
}

1 个答案:

答案 0 :(得分: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);
}