Servlet访问Web资源的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012219371/article/details/85211511

项目结构如下:
在这里插入图片描述

src目录下有个config.properties文件,src目录下的文件最终会被打包进WEB-INF/classes/目录下。在web目录下有个config目录,该目录下也有个config.properties文件。这些文件与目录最终在tomcat中的结构如下:

webapps
	Servlet
		config
			config.properties
		WEB-INF
			classes
				x.y.servlet
				config.properties			
			web.xml
		index.jsp

方式一

InputStream is=new FileInputStream("src/config.properties");

通过该种方式访问不到,因为这里的路径是相对路径,FileInputStream的相对路径是根据jre来确定的,因为这里是web项目,jre最后会交给tomcat来管理,所以这里相对的路径是tomcatbin目录。如果想访问到,需要在bin目录下新建src目录,并把config.properties拷入。

方式二

ServletContext context=getServletContext();
InputStream is=new FileInputStream(context.getRealPath("config/config.properties"));

getRealPath方法获取的是绝对路径,context.getRealPath("")获取的路径是tomcat安装目录/webapps/Servlet/context.getRealPath("config/config.properties")获取的路径是tomcat安装目录/webapps/Servlet/config/properties。通过这种方式可以访问到。

方式三

ServletContext context=getServletContext();
InputStream is=context.getResourceAsStream("config/config.properties");

ServletContextgetResourceAsStream方法相对的目录是tomcat安装目录/webapps/Servet/,通过这种方式可以访问到。

方式四

InputStream is=this.getClass().getClassLoader().getResourceAsStream("../../config/config.properties");

通过getClassLoader方法获得类加载器,再调用类加载器的getResourceAsStream方法。类加载器的getResourceAsStream方法相对的目录是tomcat安装目录/webapps/Servet/WEB-INF/classes/目录。所以需要使用../../回到上上层目录才能访问到。

猜你喜欢

转载自blog.csdn.net/u012219371/article/details/85211511