zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }
  • 相关阅读:
    使用BitMap进行海量数据去重
    记一次std::process::Child使用过程中碰到的问题
    我的第一篇rust博客
    优秀编程习惯总结
    利用generator模拟协程完美解决异步回调问题
    polymer框架在代码中动态创建需要支持内容分发的自定义元素并挂载到文档中
    属于自己的完美web服务器完成
    web components折腾记
    内边距的妙用
    用js修改带!important的css样式
  • 原文地址:https://www.cnblogs.com/cgj1994/p/9851538.html
Copyright © 2011-2022 走看看