ServletContext
1、作用
解决不同用户之间数据共享问题
2、特点
- 由服务器创立
- 所有用户共享同一个ServletContext对象
- 所有的Servlet都能够拜访到ServletContext中的属性
- 每一个web我的项目对应的是一个ServletContext
3、 用法
public class ContextServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //3种形式获取ServletContext对象 ServletContext sc1 = this.getServletContext();//罕用 ServletContext sc2 = this.getServletConfig().getServletContext(); ServletContext sc3 = request.getSession().getServletContext(); //设置属性 sc1.setAttribute("name","zhangsan"); }}
public class ContextServlet2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext sc = this.getServletContext(); //获取在contextServlet类中设置的属性 String name = (String) sc.getAttribute("name"); System.out.println(name);//zhangsan }}