JavaWeb之ServletContext域对象

ServletContext(贯穿整个WEB项目)

 

代表是一个web应用的环境(上下文)对象,ServletContext对象 内部封装是该web应用的信息。

ServletContext就是一个域对象,下边是域对象操作的函数:

  保存数据:setAttribute()

  获取数据: getAttribute()  

  删除数据: removeAttribute()  

实例:

 servlet1

public class servlet1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.得到域对象
        ServletContext context = this.getServletContext();
        
        //2.把数据保存到域对象中
        //context.setAttribute("name", "eric");
        context.setAttribute("student", new Student("jacky",20));
        System.out.println("保存成功");
    }

}


class Student{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [age=" + age + ", name=" + name + "]";
    }
  

servlet2

public class servlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.得到域对象
        ServletContext context = this.getServletContext();
        
        //2.从域对象中取出数据
        //String name = (String)context.getAttribute("name");
        Student student = (Student)context.getAttribute("student");
        //System.out.println("name="+name);
        
        System.out.println(student);
    }

}

 

posted @ 2018-11-19 22:35  元气满满01  阅读(355)  评论(0编辑  收藏  举报