ServletContext常用方法2-共享数据

发布时间 2023-03-22 21:14:13作者: 唯?独爱你

 

 

public class MyServlet2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取servletcontext
        ServletContext context = getServletContext();

        // 设置共享数据
        context.setAttribute("username", "zs");

        // 获取共享数据(在其它的servlet中使用context.getAttribute()方法也可以获取到值)
        context.getAttribute("username");

        // 删除共享数据(在其它的servlet中使用context.removeAttribute()方法也可以删除值)
        context.removeAttribute("username");
    }

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

}