在tomcat中设置网络访问的虚拟路径和使用JDNI设置文件路径常量

第一步:

在server.xml文件里面添加文件夹虚拟目录(注:使用new FIle("/home")创建的文件的绝对路径在windows和linux下是用区别的,windows下是对应的虚拟路径地址,而linux下不会自动转换成server.xml设置的磁盘路径)

 <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
       <!-- 设置图片虚拟路径[访问时路径为] 注:linux下没有盘D盘的概念,所以直接是docBase="/home" -->     
        <Context docBase="D:/home"  path="/home"  reloadable="true" debug="9"/>  
      </Host>

第二步:

在server.xml文件里面使用JDNI创建文件路径常量

   <Environment 
           name="srcPath" 
           value ="/home/yibangyilive/src/" 
           override="false"
           type="java.lang.String"   
        /> 

第三步:在context.xml中引用

 <ResourceLink name="srcPath" global="srcPath" type="java.lang.String"/>

第四步:在项目的web.xml中引用

   <resource-ref>
      <description>src文件路径</description> 
      <res-ref-name>srcPath</res-ref-name> 
      <res-type>java.lang.String</res-type>
      <res-auth>Container</res-auth>
      <res-sharing-scope>Shareable</res-sharing-scope>
   </resource-ref>


第五步:在java中引用

 static {
	    	 try {       
	             //初始化查找命名空间
	             Context ctx = new InitialContext();   
	             //参数java:/comp/env为固定路径   
	             Context envContext = (Context)ctx.lookup("java:/comp/env");  
	             //参数srcPath为数据源和JNDI绑定的名字
	          
                  String   srcPath = (String)envContext.lookup("srcPath");  
} catch ( Exception e) { e.printStackTrace(); } }
 
 


猜你喜欢

转载自blog.csdn.net/weiqingsong150/article/details/76615690