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