Black Horse day03 configuration file path problem, black horse day03
1. How to get the path of the configuration file in a Servlet.
Package com. itheima; import java. io. file; import java. io. fileReader; import java. io. IOException; import java. util. properties; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class Demo4Servlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// File file = new File ("config. properties "); // System. out. println (file. getAbsolutePath (); // The directory where the application runs. The web application runs in the bin directory of tomcat. Properties pro = new Properties (); String path = this. getServletContext (). getRealPath ("config. properties "); // use getRealPath to obtain the real path System. out. println (path); pro. load (new FileReader (path); System. out. println (pro. getProperty ("name");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
If the relative path and absolute path are written, the path will be relative to the directory started by the program. In the web environment, the directory started by tomcat is tomcat/bin. All resources cannot be found.
If you write the hard disk path, you can find the resource. However, if you change the publishing environment, the hard disk path may be incorrect.
To solve this problem, the getRealPath method is provided in ServletContext, the underlying layer of this method Concatenates the hard disk path of the current web application before the input path to obtain the hard disk path of the current resource, even if the publishing environment is changed, the underlying method can also obtain the correct web application path, which is always the correct resource path.
This. getServletContext (). getRealPath ("config. properties ")
2. Obtain the path of the configuration file from a non-Servlet File.
The directory where the class bytecode file is located. Use String path = Demo1.class. getClassLoader (). getResource (). getPath (); to get the directory where the tomcat classes folder is located.
Then I can put the configuration file in the upper-level directory of the "../config. properties" -- classes folder under the WEB-INF.
Src: "config. properties" -- directory of the classes folder
Package: "com/itheima/config. properties"
Webroot: "../config. properties" -- the upper-level directory of classes