ServletContext Object 1, Function: Javaweb a global variable applied, an application has only one ServletContext object, when the application starts, the container will create the object 2, get the ServletContext object reference 3, Applying the ServletContext feature, this object can be viewed as the Explorer 4 for the entire Web application, and the application implements the global parameters of the Web app for data sharing between multiple Servlets
Demo1 storing parameters into an object
Package Com.itheima;import Java.io.ioexception;import Javax.servlet.servletconfig;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 ServletContextDemo1 extends HttpServlet {@Overrideprotected void doget (HttpServletRequest req, httpservletresponse RESP) throws Servletexception, IOException {//Get ServletConfig Object ServletConfig config=getservletconfig ();// Create ServletContext objects based on ServletConfig objects ServletContext context=config.getservletcontext ();// Add properties and property values to the ServletContext object Context.setattribute ("abc", "Hello");} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { Doget (REQ,RESP);}}
DEMO2 Fetching Data
Package Com.itheima;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 ServletContextDemo2 extends HttpServlet {@Overrideprotected void doget (HttpServletRequest req, httpservletresponse RESP) throws Servletexception, IOException {//Create ServletContext Object ServletContext context=getservletcontext ();// Get the name of the property in the ServletContext object, receive Object O=context.getattribute ("ABC") with object,//print System.out.println (o);} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { }}
If you fetch the data first (execute DEMO2), the null is taken out, and if the data is stored first (DEMO1), the contents are taken out.
Defining Global Variables
Code <!--in Web. XML Define global parameters--<context-param> <param-name>url</param-name> < param-value>jdbc:mysql:///test</param-value> </context-param> <context-param> <param-name >username</param-name> <param-value>root</param-value> </context-param> < context-param> <param-name>password</param-name> <param-value>123</param-value> </ Get enumeration Name=context.getinitparameternames () in Context-param>//java, while (Name.hasmoreelements ()) { System.out.println ("Demo2:" +context.getinitparameter ((String) name.nextelement ()));
ServletContext when global variables are used