0

From my website this servlet below gets called number of times and every time it has to store a value in vector. But I dont want the vector to lose its previous contents once the servlet execution is complete. Like a shopping cart.

public void putValues(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
 {
Vector<Object> vector = new Vector<Object>();
 vector.add(request.getParameter("UID"));
 }

Any ideas?

4

4 回答 4

3

不要在每次调用该方法时都创建一个新的 Vector,使用实例变量。

private Vector<Object> vector = new Vector<Object>();    

public void putValues(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
     {
     vector.add(request.getParameter("UID"));
     }
于 2012-11-21T08:40:25.393 回答
1

每次调用该方法时都会创建一个新Vector实例。

此类情况通常通过将此类对象保留在HttpSession对象中来处理。

我还建议您使用ArrayList而不是 Vector,或者Collections.synchronizedList()如果您确实需要List.

于 2012-11-21T08:42:27.430 回答
1

您显然应该使用 HttpSession。

doXXX(...){
    Object data = request.getSession().getAttribute("data");
    if(data==null){
       request.getSession().setAttribute("data", new Vector());
    }

然后,每次调用 servlet 时,使用:

((Vector)(request.getSession().getAttribute("data"))).add(request.getParameter("UID"))
于 2012-11-21T08:43:42.243 回答
0

您可以将矢量内容存储在临时文本文件中

于 2012-11-21T08:40:43.897 回答