1.ServletContext

Web容器在启动的时候,它会为每个Web程序都创建一个对应的ServletContext对象,它代表了当前的Web应用

作用:

  • 共享数据
    • 我在一个Servlet中保存的数据,可以在另外一个Servlet中拿到

1.1目录配置

1.2web.xml

<?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">

  <display-name>Welcome to Tomcat</display-name>
  <description>
    Welcome to Tomcat
  </description>
  <!--注册Servlet-->
<servlet>
  <servlet-name>HelloServlet</servlet-name>
  <servlet-class>com.xf2021.servlet.HelloServlet</servlet-class>
  
</servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>Getcontext</servlet-name>
    <servlet-class>com.xf2021.servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Getcontext</servlet-name>
    <url-pattern>/get</url-pattern>
  </servlet-mapping>
</web-app>

1.3HelloServlet

package com.xf2021.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username="xiaofei";//数据
        context.setAttribute("username",username);//将一个数据保存在ServletContext中,名字为:username,值为:username



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

1.4GetServlet

package com.xf2021.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext data = this.getServletContext();
        resp.setContentType("text/html; charset=utf-8");
        String username = (String) data.getAttribute("username");
        resp.getWriter().println("名字为:"+username);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

2.结论

ServletContext相当于一个保存全局数据的一个容器,保存在其中的数据任意的Servlet都可以访问,读取,写入,Servlet之间数据交互ServletContext就是一座桥梁