ServletContext域对象
场景:假设某个web服务,有两个servlet分别是servlet1和servlet2,servlet1要传参数name=zhangsan传送给servlet2,传统方法如下:
servlet1端:用response.sendRedirect函数,形式如:response.sendRedirect("/Servlet2?name=zhangsan")。
servlet2端:String name = (String)request.getParameter("name");
但是如果我要传的参数是一个对象呢,例如一个student对象。这时候就需要引入域对象的概念了。
域对象:作用是用于保存数据,获取数据。可以在不同的动态资源之间共享数据。
那么,上边的场景,用域对象来解决,示意图如下:
ServletContext就是一个域对象,下边是域对象操作的函数:
保存数据:void setAttribute(java.lang.String name, java.lang.Object object)
获取数据: java.lang.Object getAttribute(java.lang.String name)
删除数据: void removeAttribute(java.lang.String name)
实例:
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); } }