How to obtain information about a global object of the servlet

Definition and role of the ServletContext:
// ServletContext: Servlet represents the global configuration object, the entire project is a ServletContext object, is shared by all Servlet

ServletContext alias: application

// get 1 getServletContext () object, the object is created in three ways to the same object
the ServletContext sc1 = this.getServletConfig () getServletContext ();.
The ServletContext sc2 = this.getServletContext ();
the ServletContext sc3 = request.getServletContext ( );


// 2. Use the ServletContext object

① // get absolute file path (important usage *), in the sense that when using IO streams need to set the file path, you can quickly get with this method
String realPath = sc1.getRealPath ( "img / 1.jpg");
System.out.println (realPath);


② // get global configuration information (initialization or acquisition request parameters)
String in sc1.getInitParameter = ( "Gender");
System.out.println (in);

Set global initialization parameters are as follows:

Set in the web.xml file, using the global configuration information

Note: is provided (similar to) the following information in addition to <servlet> tag

<context-param>
<param-name>gender</param-name>
<param-value>man</param-value>
</context-param>

③ // context path (context root / context path): the project path name of the directory or visit the project deployed in tomcat / webapps's
String contextPath = sc1.getContextPath ();
System.out.println (contextPath);


④ // path traversal resource in a folder
the Set <String> resourcePaths = sc1.getResourcePaths ( "/ IMG");
for (String String: resourcePaths) {
System.out.println (String);
}

⑤ // set some data stored in the ServletContext (important usage *)
sc1.setAttribute ( "msg", "the Hello");
System.out.println (. This.getServletContext () getAttribute ( "msg"));

Guess you like

Origin www.cnblogs.com/su-chu-zhi-151/p/11200154.html