ly_jewel
-kric-
采纳率100%
2019-05-27 19:04

创建List对象,老是报错The left-hand side of an assignment must be a variable?

想利用List实现向数据库中插入一堆数据,但是创建List对象时出错。
List list = (List)session.getAttribute("listname");
if(list==null)
List list = new ArrayList(); //???The left-hand side of an assignment must be a variable?
list.add(one);
session.setAttribute("listname", list);

    完整代码
package servlet;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.St;

/**
 * Servlet implementation class Insert_2
 */
@WebServlet("/insert_2")
public class Insert_2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ServletRequest session;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Insert_2() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String xh = request.getParameter("xh");
        String xm = request.getParameter("xm");
        double cj = Double.parseDouble(request.getParameter("cj"));

        String xz = request.getParameter("xz");

        St one = new St(xh, xm, cj);

        List list = (List)session.getAttribute("listname");
        if(list==null) 
            List<St> list = new ArrayList<St>();   //???
        list.add(one);
        session.setAttribute("listname", list);

        if(!xz.equals("no")) {
            request.setAttribute("aaa", list);
            RequestDispatcher rd = request.getRequestDispatcher("insert_22");
            rd.forward(request, response);
            System.out.println(xz+"结束");
        }
        else {
            RequestDispatcher rd = request.getRequestDispatcher("input_insert1.jsp");
            rd.forward(request, response);
            System.out.println(xz+"继续");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • wojiushiwo945you 毕小宝 2年前

    前面已经定义过 list 了,正确代码应该是:

     if(list==null) {
                 list = new ArrayList<St>();   //???
    }
    
            list.add(one);
    
    

    如果从会话中获取的 list 属性为空,就重新 new 一个。

    点赞 评论 复制链接分享