ServletContext对象(2)、ServletContext域对象

ServletContext对象:
一、ServletContext对象的核心API(作用)
4、域对象有关的方法
1)域对象:作用是用于保存数据,获取数据。可以在不同的动态资源之间共享数据。
2)案例:想要从Servlet1向Servlet2传送数据

方案一:
Servlet1                                                    Servlet2
name=eric                     
response.sendRedirect("/Servlet2?name=eric") get方式          String request.getParameter("name");

方案1: 可以通过传递参数的形式,共享数据。局限:只能传递字符串类型。
方案2: 可以使用域对象共享数据,好处:可以共享任何类型的数据!

ServletContext就是一个域对象!
a)存取字符串类型的数据:

b)存取对象:

//ServletContext存
package sram.context;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextDemo3 extends HttpServlet {
    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        //得到域对象
        ServletContext context = this.getServletContext();
        //把数据保存到域对象中
        context.setAttribute("Student",new Student("Endeavor",22));
        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){
        this.name = name;
        this.age =age;
    }
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}
//ServletContext取
package sram.context;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

2)void setAttribute(java.lang.String name, java.lang.Object object) 保存数据
3)java.lang.Object getAttribute(java.lang.String name) 获取数据
4)void removeAttribute(java.lang.String name) 删除数据
5)ServletContext域对象:作用范围在整个web应用中有效!
所有域对象:
HttpServletRequest 域对象、ServletContext域对象、HttpSession 域对象、PageContext域对象

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值