1.

ServletContext sc = this.getServletContext();

//获取应用的路径

String contextPath = sc.getContextPath();// "/W06"

//第一种写法:通过找到ServletContext

//response.sendRedirect(contextPath + "/index.html");

//推荐写法 通过request

response.sendRedirect(request.getContextPath() + "/index.html");


2.

ServletContext sc = this.getServletContext();

//向域对象中添加数据,key-value形式,先运行Demo3,在运行Demo3_2

sc.setAttribute("name", "zhangsan");

//如果key值相同,会覆盖原来的值

sc.setAttribute("name", "lisi");

Dog dog = new Dog("wangcai", 2);

sc.setAttribute("dog", dog);

----------------》》》》:

//在其他servlet中找到对应属性

ServletContext sc = this.getServletContext();

//根据key值从域中获取对应的value

String name = (String)sc.getAttribute("name");

System.out.println(name);

Dog dog = (Dog)sc.getAttribute("dog");

System.out.println(dog.getName());

你可能感兴趣的:(域)