关于java:Servlet之ServletContext和ServletConfig

52次阅读

共计 1122 个字符,预计需要花费 3 分钟才能阅读完成。

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
    }
}

正文完
 0