关于context全局对象的问题.

来源:3-3 综合训练-实现新增员工功能

超人迪加123

2019-06-15 21:08:06

这个是ListServlet路径/list

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext context = request.getServletContext();

              这里故意没有添加判断条件

            List<Employee> employees = new ArrayList<Employee>();
            employees.add(new Employee(7782,"张晓涛","研发部","研发工程师",7780.00f));
            employees.add(new Employee(7839,"张丽","研发部","运维工程师",8820.00f));
            context.setAttribute("employees", employees);
            request.getRequestDispatcher("/employee2.jsp").forward(request, response);
    }

employee.jsp页面正常.

然后在后面 CreateServlet 里面获取 list 列表时,发生了空指针异常

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String empno = request.getParameter("empno");
        String ename = request.getParameter("ename");
        String department = request.getParameter("department");
        String job = request.getParameter("job");
        String salary = request.getParameter("salary");
        Employee emp = new Employee(Integer.parseInt(empno),ename,department,job,Float.parseFloat(salary));
        ServletContext context = request.getServletContext();

        就在这个位置 , list 列表是空的. 想了很久没不明白.在此提问

        List<Employee> employees = (List)context.getAttribute("employees");
        employees.add(emp);
        context.setAttribute("employees", employees);
        request.getRequestDispatcher("/employee2.jsp").forward(request, response);
    }

先前对于这个判断老师有特意说到,重复生成的问题,所以加了判断语句.做练习时好奇,如果不加这个语句,每次都重复生成新的同名对象给context.setAttribute("***")设置进去会发生什么?后面就出再了空指针异常,想不明白,望各位老师及同学们赐教.

if(context.getAttribute("employees")==null){
            List<Employee> employees = new ArrayList<Employee>();
            employees.add(new Employee(7782,"张晓涛","研发部","研发工程师",7780.00f));
            employees.add(new Employee(7839,"张丽","研发部","运维工程师",8820.00f));
            context.setAttribute("employees", employees);
        }

写回答

1回答

好帮手慕阿莹

2019-06-16

同学你好,

1、请问发生空指针异常是否是因为先访问了CreateServlet呢?也就是尚未访问ListServlet初始化呢?

2、建议同学打印一下你的两个Servlet中的context,看看两个是否是同一个对象呢?

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


0

0 学习 · 9666 问题

查看课程