Common methods in ServletContext
- 2020-04-01 02:05:00
- OfStack
I. get the initialization parameters of Tomcat's Context.
1. Get the initialization parameters of setting Context in Tomcat's server.xml.
Such as:
<Context path="/testcontext" docBase="/context"
privileged="true" antiResourceLocking="false" antiJARLocking="false"
debug="0" reloadable="true">
<Parameter name="name" value="yangqisheng" />
</Context>
GetServletContext (). GetInitParameter (String name)
2. Gets the initialization parameters of the Context set in the web.xml under the project.
Such as:
<context-param>
<param-name>age</param-name>
<param-value>24</param-value>
</context-param>
GetServletContext (). GetInitParameter (String name)
2. Log Tomcat
1. Set the log file
In the server.xml file, use the logger element to set the log file.
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_log." suffix=".txt" timestamp="true"/>
Log: this.getservletcontext ().log(" test ")
Access to resource files
3.1 getResource(String parh) method: where the path must start with/and represent the root directory of the current web application. Returns a URL object that represents a resource.
3.2 getResoutceAsStream(String parh), returns the file stream. The benefit is that you can use a path relative to the root directory to access all the files in the web directory without having to know the absolute path.
For example, under web-inf, create a new file, me.properties, which reads:
Name = yangqisheng
Age = 25
this.getServletContext().getResourceAsStream("/WEB-INF/me.properties");
Properties me = new Properties();
me.load(is);
out.write(me.getProperty("name"));
out.write(me.getProperty("age"));
Then execute in the Servlet:
It will print out yangqisheng25