javaweb读取 web 应用中的资源文件

javaweb读取 web 应用中的资源文件

一、读取 web 应用中的资源文件(资源获取路径)

 

 

1、ServletContext获取资源

1.1 getRealPath

package cn.ccnu.path;  
  
import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
/* 
 * ServletContext接口的getRealPath(Stringpath)方法
 * 返回的是资源文件在服务器文件系统上的真实路径(带有盘符)。
 * 参数path代表资源文件的虚拟路径,它应该以正斜线(/)开始,"/"表示当前web应用的根目录,也可以不以"/"开始。
 */  
public class ServletContextServlet extends HttpServlet {  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
    	//当前资源:ServletContextServlet 和a.properties是在同一目录下的,
    	//   即:都是类路径【\javaee\WEB-INF\classes】下的
    	//    \javaee\WEB-INF\classes\cn\ccnu\path 下的同级文件
    	
        String path1 = this.getServletContext().getRealPath("/a.properties");//可以显示,但是路径错误  
        //路径错误的言外之意:a.properties文件的路径不是在:E:\apache-tomcat-7.0.73\webapps\javaee\a.properties
        //说明,我们写的方式存在问题!!!!!!
        String path2 = this.getServletContext().getRealPath("a.properties");
        //可以显示,但是路径错误  (原因:与path1同)
        
        //正确:
        //原因:因为a.properties文件实在cn.ccnu.path包下的,而这些java包都是在src文件夹下的。
        //而src文件夹下的文件,编译后,都是存放在   /WEB-INF/classes 目录下,所以,要显示出a.properties文件的正确路径,
        //应该把它所在的cn.ccnu.path写上,因为这样才是它的真实存放路径
        String path3 = this.getServletContext().getRealPath("/WEB-INF/classes/cn/ccnu/path/a.properties");
       
        String path4 = this.getServletContext().getRealPath("");//当前web应用的路径
        
        String path5 = this.getServletContext().getRealPath("c.properties");
        //可以显示,但是路径错误  (原因:与path1同)
        
        //不存在的文件演示path6  
        String path6 = this.getServletContext().getRealPath("2333333.txt");//错误
        //无论你的文件存在还是不存在,他都会给你是显示出路径来,所以写路径时,应该注意,一定要真实存在的文件,然后写出它所在的正确路径
        
        System.out.println(path1);  
        //   E:\apache-tomcat-7.0.73\webapps\javaee\a.properties
        System.out.println(path2); //输出的地址一样  
        //   E:\apache-tomcat-7.0.73\webapps\javaee\a.properties
        
        System.out.println(path3); 
 		// E:\apache-tomcat-7.0.73\webapps\javaee\WEB-INF\classes\cn\ccnu\path\a.properties
        System.out.println(path4);
       // E:\apache-tomcat-7.0.73\webapps\javaee
        System.out.println(path5);
        //  E:\apache-tomcat-7.0.73\webapps\javaee\c.properties
        System.out.println(path6);
        // E:\apache-tomcat-7.0.73\webapps\javaee\2333333.txt
        
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
  
}  

1.2 getResourceAsStream

package cn.ccnu.path;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 但是,此处的用法是:以/开头的相对路径 ,此时的/代表web应用
         默认从WebAPP根目录下取资源
 */
public class ServletContextServlet2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//		InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/1.txt");//成功
//		InputStream in = getServletContext().getResourceAsStream("a.properties");//失败
//		InputStream in = getServletContext().getResourceAsStream("/cn/ccnu/path/a.properties");//失败
		
//		InputStream in = getServletContext().getResourceAsStream("/a.properties");//失败
		/*
		 * 虽然,ServletContextServlet2和a.properties文件,都在/WEB-INF/classes/cn/ccnu/path/目录下,
		 * 但是,此处的用法是:以/开头的相对路径 ,此时的/代表web应用
		 *     默认从WebAPP根目录下取资源
		 *     
		 *   疑惑1:  ServletContext读取web应用中的资源文件 :
		 *   	 http://blog.csdn.net/chentiefeng521/article/details/57419954
		 *   疑惑2:Sax 中 getResourceAsStream 读取src目录下以及WEB-INF目录下的XML写法
		 *   	http://blog.csdn.net/fly_watermelon/article/details/50792979
		 */
		InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/cn/ccnu/path/a.properties");
//		InputStream in = getServletContext().getResourceAsStream("/cn/ccnu/path/a.properties");//失败
		byte[] buf = new byte[1024];
		int len = 0;
		
		File f1 = new File("d://temp1//temp1");// 创建目录
		if (!f1.exists()) {
			f1.mkdirs();
		}
		File f11 = new File(f1, "temp.txt");// 创建文件
		OutputStream out = new FileOutputStream(f11);// 方式1:成功读取
		while ((len = in.read(buf)) != -1) {
			out.write(buf, 0, len);
		}
		System.out.println("成功222...............");
		in.close();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);

	}

}

1.3 总结

(1)ServletContext接口的getRealPath(Stringpath)方法返回的是资源文件在服务器文件系统上的真实路径(带有盘符)。

参数path代表资源文件的虚拟路径,它应该以正斜线(/)开始,“/“表示当前web应用的根目录,也可以不以“/“开始。

(2)ServletContext接口的getResouceAsStream(String path)方法可以获取path指定资源的流。

参数path代表资源文件的虚拟路径,它应该以正斜线(/)开始,

/“表示当前web应用的根目录,也可以不以“/“开始。

总之:

两种都是:“/“表示当前web应用的根目录,也可以不以“/“开始。

 

参考来源:ServletContext读取web应用中的资源文件

网址:

http://blog.csdn.net/chentiefeng521/article/details/57419954

2、ClassLoader获取资源

2.1 getResourceAsStream方式

package cn.ccnu.classloaderpath;  
  

import java.io.IOException;
import java.io.InputStream;  
import java.util.Properties;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
/* 
 * ClassLoader类加载器不能通过绝对地址来加载资源,只能通过相对地址来加载资源 
 * 		但相对地址不管前面加不加/都是相当于类路径的相对地址 
 * 
 * 	注意:ClassLoaderServlet 这个java类的类全名是:cn.ccnu.classloaderpath.ClassLoaderServlet
 * 	   在类路径类【/javaee/WEB-INF/classes】下的存放地址是:cn/ccnu/classloaderpath/ClassLoaderServlet
 *    即:类的报名中的每一个'.'都是路径'/'的形式
 *  
 */  
public class ClassLoaderServlet extends HttpServlet {  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        /* 
         * 加了/,其地址是相对于类路径的相对地址 【类路径,即:/javaee/WEB-INF/classes】
         */  
//      InputStream in = this.getClass().getClassLoader().getResourceAsStream("/cn/ccnu/classloaderpath/c.properties");  
//      Properties prop = new Properties();  
//      prop.load(in);  
//      System.out.println(prop.getProperty("url"));  
          
        /* 
         * 不加/,其地址是相对于类路径的相对地址 
         */  
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("cn/ccnu/classloaderpath/c.properties");  
        Properties prop = new Properties();  
        prop.load(in);  
        System.out.println(prop.getProperty("url"));  
        /* 
         * 总结:不能使用绝对地址,而只能只用相对地址 
         * 且不管加不加/的相对地址,都是相对于类路径的相对地址 
         *  
         */  
        
      
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
  
}  

2.2 getResource方式

package cn.ccnu.classloaderpath;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClassLoaderServlet2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		  //错误
//      String path = ClassLoaderServlet.class.getClassLoader().getResource("c.properties").getPath();
//      String path = ClassLoaderServlet.class.getClassLoader().getResource("/c.properties").getPath();
    
	  //正确:
      /*
       * ClassLoader类加载器不能通过绝对地址来加载资源,只能通过相对地址来加载资源 
		         但相对地址不管前面加不加/都是相当于类路径【/javaee/WEB-INF/classes】的相对地址 
       */
      String path = ClassLoaderServlet.class.getClassLoader().
    		  getResource("cn/ccnu/classloaderpath/c.properties").getPath();
      System.out.println("path:"+path);
      //path:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/cn/ccnu/classloaderpath/c.properties
      System.out.println("-------------------------------------------------------------");
     
      System.out.println("resource:"+ClassLoaderServlet.class.getClassLoader().getResource(""));
      //读取资源的 URL 对象
      // file:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/
      System.out.println("-------------------------------------------------------------");
      
      String path2 = ClassLoaderServlet.class.getClassLoader().getResource("").getPath();
      //获取src资源文件编译后的路径(即classes路径) 
      String path3 = this.getClass().getClassLoader().getResource("").getPath();
      //获取src资源文件编译后的路径(即classes路径) 
      System.out.println("path2:"+path2);
      System.out.println("path3:"+path3);
      /*
       * path2:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/
		 path3:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/
       */
      System.out.println("-------------------------------------------------------------");
      String path4 = ClassLoaderServlet.class.getResource("").getPath();
      System.out.println("path4:"+path4);
      //缺少类加载器,获取xxx类经编译后的xxx.class路径 
     // path4:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/cn/ccnu/classloaderpath/
      System.out.println("-------------------------------------------------------------");
      String path5 = request.getSession().getServletContext().getRealPath("");
      System.out.println("path5:"+path5);
      //获取web项目的路径 
      // path5:E:\apache-tomcat-7.0.73\webapps\javaee
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);

	}

}

2.3 总结

(1)ClassLoader类加载器不能通过绝对地址来加载资源,只能通过相对地址来加载资源 。但相对地址不管前面加不加“/”都是相当于类路径【/javaee/WEB-INF/classes】的相对地址

(2)

1、xxx.class.getClassLoader().getResource(“”).getPath();

获取src资源文件编译后的路径(即classes路径:

eg:  /E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/

2、xxx.class.getClassLoader().getResource(“文件”).getPath();

获取classes路径下“文件”的路径

3、this.getClass().getClassLoader().getResource(“”).getPath();

以上两种方法的另外一种写法

4、特殊:xxx.class.getResource(“”).getPath();

缺少类加载器,获取xxx类经编译后的xxx.class路径

 

参考来源:Javaclass.getClassLoader().getResource("")获取资源路径

网址:http://blog.csdn.net/ttx_laughing/article/details/52881452

3、Class获取资源

package cn.ccnu.classpath;  
  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.Properties;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
/* 
 * Class读取资源不能是绝对路径,只能是相对路径,又分为以/开头或者是不以/开头 
 *      1.以/开头的相对路径 ,此时的/代表类路径【类路径,即:/javaee/WEB-INF/classes】
 *      2.不以/开头的相对路径 , 此时写的时候,相对的是当前资源文件所在的路径。
 *                     eg:即(此处当前资源):/javaee/WEB-INF/classes/cn/ccnu/classpath
 */  
public class ClassServlet extends HttpServlet {  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        /* 
         * 1.以/开头的相对路径 
         *      此时的/代表类路径,即:/javaee/WEB-INF/classes 
         */  
//      InputStream in = ClassServlet.class.getResourceAsStream("/cn/ccnu/classpath/b.properties");  
//      Properties porp = new Properties();  
//      porp.load(in);  
//      System.out.println(porp.getProperty("url"));
    	
    	
        /* 
         * 2.不以/开头的相对路径 
         *      相对的是当前资源文件所在的路径,此时相对的是:类ClassServlet.class的路径,
         *      即:\javaee\WEB-INF\classes\cn\ccnu\classpath (电脑下的路径写法)
         *      即:/javaee/WEB-INF/classes/cn/ccnu/classpath (java下的一种路径写法)
         */  
        InputStream in = ClassServlet.class.getResourceAsStream("b.properties");  
        Properties porp = new Properties();  
        porp.load(in);  
        System.out.println(porp.getProperty("url"));  
  
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
  
}  

总结:

Class读取资源不能是绝对路径,只能是相对路径,又分为以/开头或者是不以/开头

1.以/开头的相对路径 ,此时的/代表类路径【类路径,即:/javaee/WEB-INF/classes

2.不以/开头的相对路径 , 此时写的时候,相对的是当前资源文件所在的路径。

 eg:即(此处当前资源:src目录下的:cn.ccnu.classpath.ClassServlet)

/javaee/WEB-INF/classes/cn/ccnu/classpath                                                      

 

二、servlet和el表达式中的一些路径写法

1、servlet中路径写法

//1.路径1 getContextPath()得到工程名

      String contextPath = request.getContextPath();

      //--路径:/Upload_download

      System.out.println("contextPath:"+contextPath);

     

      //2.路径2 request.getSession().getServletContext().getContextPath()

      ServletContext servletContext2 =request.getSession().getServletContext();

      //--路径:/Upload_download得到工程名

      System.out.println("getContextPath2:"+servletContext2.getContextPath());

     

      //3.路径3 getServletContext().getContextPath()

      ServletContext servletContext = this.getServletContext();

      //--路径:/Upload_download得到工程名

      System.out.println("getContextPath:"+servletContext.getContextPath());

     

      //4.路径4  servletContext.getRealPath("/WEB-INF/info.txt")

      String realPath =servletContext.getRealPath("/WEB-INF/info.txt");

      //--路径:E:\apache-tomcat-7.0.73\webapps\Upload_download\WEB-INF\info.txt

      System.out.println("realPath:"+realPath);

     

      //5.路径5  getServletPath()

      //返回当前页面所在目录下全名称

      String servletPath =request.getServletPath();

      //路径:/upload

      System.out.println("servletPath:"+servletPath);

     

      //6、返回包含工程名的当前页面全路径

      String requestURI =request.getRequestURI();

      //路径:/Upload_download/upload

      System.out.println("requestURI:"+requestURI);

     

      //7、返回IE地址栏地址

      StringBuffer requestURL =request.getRequestURL();

      //路径:http://localhost:8080/Upload_download/upload

      System.out.println("requestURL:"+requestURL);

 

 

2、el表达式中路径写法

http://localhost:8080/test/success.jsp

等价于

${pageContext.request.contextPath }/ test/success.jsp

说明:${pageContext.request.contextPath }作用:取出部署的应用程序名

 

 

三、web开发中 路径的写法小结

/*

 *   web开发中 路径的写法小结

 *

 *     你 每次写路径时,你自问 自,  你写路径是给谁 用的 ?

 *    

 *     上来 先写个  /再说 .

 *    

 *     //给 浏览器 用的   ----- / ,那么 / 表示的是当前的主机名

 *     //给  web应用的  -----/ ,  那么/ 表示当前 web应用的 根目录

 */

public class PathSummaryServlet extends HttpServlet {

 

   public void doGet(HttpServletRequest request,HttpServletResponse response)

         throws ServletException, IOException {

     

     

      // 1.  转发的时候 ----给  web应用的

   request.getRequestDispatcher("/servlet2").forward(request, response);

     

      //2. 重定向的时候   ----给 浏览器用的 

      response.sendRedirect("/day11/1.html");

     

      //3. 读取 web应用下资源文件的时候  ---web应用根目录下有一个 1.txt文件    ----给  web应用的

      getServletContext().getRealPath("/1.txt");

     

      // 4.  表单提交数据的时候    ----给 浏览器用的

      // <form action="/day11/servlet2">

     

      // 5. 超链接 a标签的时候   ----给 浏览器用的

      //  <a href="/day12/1.jsp"></a>

     

      // 6. 写了img 标签,src    ----给 浏览器 用的

      // <img src="/day11/checkimage">

     

     

   //7. url重写      ----给 浏览器 用的http://.../servlet;jsessionid=KSDFLKDSJFLKJDS

      response.encodeURL("/day11/servlet2");

     

//    =========================================================

     

      // 8. 使用类加载器获得文件的路径的时候  ----特殊

 

ClassLoader类加载器不能通过绝对地址来加载资源,只能通过相对地址来加载资源。但相对地址不管前面加不加/都是相当于类路径的相对地址

类路径:【/javaee/WEB-INF/classes

备注:当前项目是:javaee

14.txt文件是src目录下的文件(26.jpg文件是src目录下的文件

 

1PathSummaryServlet.class.getClassLoader().getResource("4.txt")

//获取src资源文件编译后的路径(即classes路径:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/4.txt

 

 

2

InputStream in = PathSummaryServlet.class.getClassLoader().getResourceAsStream("6.jpg");

//获取src资源文件编译后的路径(即classes路径:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/6.jpg

   

 

3

InputStream in2 = getServletContext().getResourceAsStream("/WEB-INF/classes/6.jpg");

ServletContext接口的getResouceAsStream(String path)方法可以获取path指定资源的流。

参数path代表资源文件的虚拟路径,它应该以正斜线(/)开始,“/”表示当前web应用的根目录,也可以不以“/”开始。

      

 

4

PathSummayServlet.class.getResource("/4.txt");

//缺少类加载器,获取xxx类经编译后的xxx.class路径

即:关于src下的一个类:cn.ccnu.classloaderpath.ClassLoaderServlet

 

Stringpath4 = ClassLoaderServlet.class.getResource("").getPath();

System.out.println("path4:"+path4);

path4:/E:/apache-tomcat-7.0.73/webapps/javaee/WEB-INF/classes/cn/ccnu/classloaderpath/

 

   }

 

四、参考文章

1、文章1:Java class.getClassLoader().getResource("")获取资源路径

网址:http://blog.csdn.net/ttx_laughing/article/details/52881452

2、文章2:关于Class.getResource和ClassLoader.getResource的路径问题

网址:https://www.cnblogs.com/yejg1212/p/3270152.html

3、文章3:javaweb中路径的书写总结

网址:http://blog.csdn.net/bbb695480667/article/details/53838321

4、文章4:ServletContext读取web应用中的资源文件

网址:http://blog.csdn.net/chentiefeng521/article/details/57419954

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值