web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用。
- 共享数据
- 我在这个Servlet中保存的数据,可以在另外一个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;
import java.nio.charset.StandardCharsets;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getServletContext() Servlet上下文
ServletContext context = this.getServletContext();
String name = "秦疆";//数据
//将一个数据保存在了ServletContext中,名字为(键为):username;值为:上面创建的name
context.setAttribute("username",name);
System.out.println("Hello");
}
}
- 读取数据的类
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 context = this.getServletContext();
String username = (String) context.getAttribute("username");
//处理中文乱码
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- web.xml
hello com.kuang.servlet.HelloServlet hello /hello getc com.kuang.servlet.GetServlet getc /getc
- 测试访问结果
先访问:http://localhost:8080/s3/hello
HelloServlet 设置了ServletContext的参数
后访问:http://localhost:8080/s3/getc
GetServlet 获取到HelloServlet 设置的ServletContext的参数
如果直接访问http://localhost:8080/s3/getc时,ServletContex中还没有设置参数,因此值为null



