日期:2014-05-17  浏览次数:20715 次

去ServletContext中的数据为null
本帖最后由 wanaqiang 于 2013-10-13 11:32:42 编辑

public class Demo6 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletExceptionIOException {
//两种获取servletContext对象的方式
ServletContext context = this.getServletConfig().getServletContext();
ServletContext context1 = this.getServletContext();
//servlet6带数据给servlet7(用context对象实现数据共享)
context1.setAttribute("name", "zhangsan");
}


public class Demo7 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

ServletContext  context = this.getServletContext();
//context.setAttribute("data", 123);
System.out.println(context.getAttribute("name"));
}



访问Demo7打印为NULL

代码是没有问题的我使用教程代码也是这种情况 。。。。纠结中 

------解决方案--------------------
可以的啊,首先你要先访问你的Demo6然后到Demo7,ActionContent是上下文的意思,有上文才有下文的,你没有访问过Demo6,你就直接跑到Demo7肯定是空值的,这个要注意的。