Servlet中加获取工程文件的三种方式

一,加载配置文件的三种方式

@WebServlet("/servletDemo1")
public class servletDemo1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * ServeltContext 的getServletContext()获取的默认路径为该项目在Tomcat中的路径
     * 即D:\javawebtool\apache-tomcat-8.5.40\wtpwebapps\web04\
     * ClassLoader 的getClassLoader()获取的默认路径为项目在Tomcat中工程下的WEB-INFO\classes目录
     * 即D:\javawebtool\apache-tomcat-8.5.40\wtpwebapps\web04\WEB-INFO\classes
     * 
     * 
     * request对象中包含请求的信息
     * response响应数据给浏览器
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        //创建属性对象
        Properties p = new Properties();
        
        //获取web工程文件方式一:相对路径方式,获取文件在服务器上的绝对路径
        //config1.properties放在了src下.D:\javawebtool\apache-tomcat-8.5.40\wtpwebapps\web04下没有src目录
        //String path = context.getRealPath("src/config1.properties");
        String path = context.getRealPath("config.properties");
        
        //下面一行代码会报错,路径问题 ,这里的相对路径是根据jre来确定的,但现在是一个web工程,jre后面会由Tomcat管理,相对路径为Tomcat里面bin目录
        InputStream it = new FileInputStream(path);
        
        //获取web工程文件方式二:转换为流对象。前面隐藏当前工程的根目录
        //InputStream it = context.getResourceAsStream("config.properties");
        
        //获取web工程文件方式三:类加载器方式。this.getClass()获取当前类的class;.getClassLoader()获取类加载器对象。用把当前类加载到虚拟机的那个类加载器去获取资源
        //InputStream it = this.getClass().getClassLoader().getResourceAsStream("../../config.properties");
        p.load(it);
        String string = p.getProperty("name");
        System.out.println(string);
    }

 

posted @ 2019-08-07 20:43  Noperx  阅读(213)  评论(0编辑  收藏  举报