ServletContext对象的学习

发布时间 2023-10-16 19:57:25作者: KukiHistory

一、新建了一个模块servlet-02,需要改变web.xml头部,并且改变tomcat配置,war尽量用哪个打哪个

头部代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
metadata-complete="true">

</web-app>

 二、同样创建一个类继承HttpServlet类并且在xml中写好Servlet的配置和路径

三、ServletContext对象,在web容器启动时,他会为每一个servlet创建一个对应的ServletContext对象,这个对象代表了当前的应用

它有很多应用,这边讲

数据共享:在一个Servlet中保存的数据,可以在另外一个Servlet中拿到,这就实现了数据共享。下面是实例操作

 再创建一个新的类,一样继承了HttpServlet类,重写方法,并且可以创建一个ServletContext对象来拿到刚刚保存的数据

 写完两个类之后,我们还要写他们的web.xml映射,这样网页才能访问到

 四、结果

如果直接访问getc,那么数据是空的,因为之前给数据的类还没访问调用

 要先访问hello  再访问getc  这样才能拿到我们的数据