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域对象