The concept ServletContext object
ServletContext object implement some common data among different memory users
Features:
- The server creates
- Users share
Scope : The entire project within
Life Cycle : The server starts to shut down the server
Get ServletContext object
The first way
- ServletContext sc=this.getServletContext();
The second way
- ServletContext sc2=this.getServletConfig().getServletContext();
The third way
- ServletContext sc3=req.getSession().getServletContext();
Use ServletContext object for data sharing
data storage
- sc.setAttribute(String name, Object value);
data collection
- sc.getAttribute ( "str") returns the type Object
note:
- Different users can access the data to ServletContext object.
- Acquired data does not exist return null.
Get in touch with the configuration global configuration data
Some web project needs to keep some users to share static data, then we put these data configuration in web.xml.
Obtain
- sc.getInitParameter (String name); Return Value web.xml configured in accordance with Global Data key name, return type String.
- sc.getInitParameterNames (); returns the key enumeration
- If the data does not exist return null.
Configuration
Add the following code in web.xml
Note: a group <context-param> tag can store a set of key-value pairs of data, a plurality of sets can declare multiple <context-param> are stored.
<context-param> <param-name>name</param-name> <param-value>value</param-value> </context-param>
Role : static data and code decoupling.
Absolute path to get the project under webroot resources.
- Route entry in the root directory path for the project // get root directory, path parameters; String path = sc.getRealPath (String path)
Get a stream object resources under the webroot
- InputStream is = sc.getResourceAsStream(String path);
note:
- In this way can only get a stream object resources under the project root directory, the file stream object class is required to obtain class loader
- path parameter is a path to the root directory items such as: /doc/1.txt