web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
1. 共享数据
在一个servlet中保存在ServletContext的数据,可以在另外一个servlet中拿到。
- 写入数据
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//往ServletContext里面写入哈哈怪
ServletContext context = this.getServletContext();
context.setAttribute("username","哈哈怪");
Object username = context.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
- 读取数据
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取ServletContext里面的username值
ServletContext context = this.getServletContext();
Object username = context.getAttribute("username");
System.out.println(username);
//设置网页的编码和类型
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
最后在web.xml里面配置相应的servlet类运行即可
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="4.0"
metadata-complete="true">
<!-- 配置servlet的注入ServletContext启动注入-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.hwh.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getContext</servlet-name>
<servlet-class>com.hwh.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getContext</servlet-name>
<url-pattern>/getContext</url-pattern>
</servlet-mapping>
</web-app>