利用ServletContext对象实现多个Servlet之间的数据共享


import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                    ServletContext sc = getServletContext();
                    sc.setAttribute("p", "pp");
                    response.getOutputStream().write("放了".getBytes());
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                    doGet(request, response);
        }
}



import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ServletDemo4 extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                    ServletContext sc = getServletContext();
                    String obj = (String) sc.getAttribute("p");
                    response.getOutputStream().write(obj.getBytes());
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                    doGet(request, response);
        }
}




你可能感兴趣的:(小例子Demo)