Common Methods in ServletContext

Source: Internet
Author: User

1. Obtain the initialization parameters of Tomcat Context.
1. Obtain the initialization parameters of Context in Tomcat server. xml.
For example:

Copy codeThe Code is as follows: <Context path = "/testcontext" docBase = "/context"
Privileged = "true" antiResourceLocking = "false" antiJARLocking = "false"
Debug = "0" reloadable = "true">
<Parameter name = "name" value = "yangqisheng"/>
</Context>

Method: getServletContext (). getInitParameter (String name)
2. Obtain the initialization parameters for setting Context in the web. xml file of the project.
For example:Copy codeThe Code is as follows: <context-param>
<Param-name> age </param-name>
<Param-value> 24 </param-value>
</Context-param>

Method: getServletContext (). getInitParameter (String name)

Ii. Record Tomcat logs
1. Set the log file
In the server. xml file, use the logger element to set the log file.

Copy codeThe Code is as follows: <Logger className = "org. apache. catalina. logger. FileLogger"
Prefix = "localhost_log." suffix = ". txt" timestamp = "true"/>

Write log: this. getServletContext (). log ("test ")

3. Access resource files
3.1 getResource (String parh) method: path must start with/, representing 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. This advantage is that you can access all files in the web directory using the path relative to the root directory without having to know the absolute path.
For example, creating a file me. properties in a WEB-INF with the content:
Name = yangqisheng
Age = 25

Copy codeThe Code is as follows: 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:
Yangqisheng25 will be printed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.