1. How to get the path to 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 ());//Here is the directory where the application runs, The web app runs in Tomcat's Bin directory, Properties Pro=new properties (); String path = This.getservletcontext (). Getrealpath ("config.properties");//Use Getrealpath to get the real path System.out.println (path);p ro.load (Path) (new FileReader); System.out.println (Pro.getproperty ("name"));} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}
If you write a relative path and an absolute path, because the path will be relative to the directory that the program started--in the Web environment, the directory that Tomcat started is tomcat/bin--all resources cannot be found
If you write a hard drive path, you can find the resource, but as soon as you change the publishing environment, the hard drive path is probably wrong, and not the same.
In order to solve such a problem ServletContext provides a Getrealpath method, in which a path is passed in, the bottom of the method will be in the path of the current Web application to splice the hard disk path to get the current resource's hard drive path, even if the release environment, The bottom of the method also gets the correct path to the Web application and is always the correct path to the resource
This.getservletcontext (). Getrealpath ("Config.properties")
2. Get the path to the configuration file in a non-servlet
Use the directory where the class bytecode file resides. Even with string Path=demo1.class.getclassloader (). GetResource (). GetPath (); Get the directory where Tomcat's Classes folder is located
Then I can go through it. config file under Web-inf ". /config.properties "--classes folder's parent directory
SRC: "config.properties"--the directory where the classes folder is located
Subpackages: "Com/itheima/config.properties"
Webroot: ". /.. /config.properties "--classes Parent directory of the parent directory
Dark Horse day03 configuration file path problem