javaWeb项目之Servlet学习笔记----ServletContext的读取方法

本文详细介绍了在JavaWeb项目中如何使用ServletContext的getRealPath(), getResource(), getResourceAsStream()方法来读取web应用下的资源文件,如数据库配置文件database.properties。讨论了在【src】目录下资源的读取方式,以及类加载器在非Servlet对象读取资源时的作用。同时也提到了使用类加载器读取修改后配置文件的限制和解决方案。" 133048522,20038042,Android Activity生命周期与Kotlin反编译调试,"['Android开发', 'Kotlin语言', '应用调试', 'UI组件']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

https://www.cnblogs.com/fjdingsd/p/4846727.html

ServletContext类中有这么四个方法:

  getRealPath(String path)

  getResource(String path)

  getResourceAsStream(String path)

  getResourcePaths(String path)

  这四个方法都使用web工程下某个web资源路径的字符串表现形式作为参数,而每个方法返回不同的类型,我们通过这四个方法之一可以获取某个资源,并对其进行读取和修改操作。

 

假设我们的【myservlet】web工程中有一个数据库的配置文件:database.properties,在这个数据库中已经有了一些参数,而我们在web工程中希望读取这个配置文件中的有关信息:

  

  getResourceAsStream(String path) 

 先来看看ServletContext中的getResourceAsStream()方法,这个方法返回InputStream对象。由于我们的配置文件为properties文件,所以可以用Properties对象来装载这个输入流,代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/database.properties");
        
        Properties prop = new Properties();
        prop.load(in);
        
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }

getRealPath() 

接下来看看ServletContext中的getRealPath()方法,这个方法返回String对象。由于我们的配置文件为properties文件,所以可以用Properties对象来装载这个输入流,代码如下:

ServletContext context = this.getServletContext();
        String filePath = context.getRealPath("/database.properties");
        
        FileInputStream fis = new FileInputStream(filePath);
        Properties prop = new Properties();
        prop.load(fis);
        
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);

使用getRealPath()方法的好处在于这个方法还可以获取文件名,而getResourceAsStream()方法就只能获取文件流了。例如获取文件名:

ServletContext context = this.getServletContext();
        String filePath = context.getRealPath("/WEB-INF/web.xml");
        System.out.println(filePath);
        
        if(filePath == null) {
            System.out.println("所找文件不存在!");
        }
        String fileName = filePath.substring(filePath.lastIndexOf("\\"));
        System.out.println("文件为:"+fileName);

getResource()

 

接着来看看ServletContext中的getResource()方法,这个方法返回URL对象。而URL对象具有打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream的openStream()方法。由于我们的配置文件为properties文件,所以可以用Properties对象来装载这个输入流,代码如下:

 

 1      ServletContext context = this.getServletContext();
 2         URL fileUrl = context.getResource("/database.properties");
 3         InputStream in = fileUrl.openStream();
 4         
 5         Properties prop = new Properties();
 6         prop.load(in);
 7         
 8         String url = prop.getProperty("url");
 9         String username = prop.getProperty("username");
10         String password = prop.getProperty("password");
11         System.out.println(url);
12         System.out.println(username);
13         System.out.println(password);

 

最后在浏览器中访问这个Servlet,那么在MyEclipse的控制台上能看到的数据正好是database.properties中我们配置的信息:

 

以上说完了几种通过ServletContext对象来读取web应用下的某个资源文件,只要通过读取的方法,并将资源相对于web工程的路径作为参数传入其中便可。我们上述的例子都是直接在web工程中,或者web工程的某个目录下,而如果我们把某个web资源放置在MyEclipse中的【src】目录中,那么该如何读取呢:

  

  我们说过,这个web应用在发布时,会将【src】目录下的.java文件编译成为.class字节码文件,由服务器自动将这些字节码文件放置在该web应用中的【WEB-INF】下的【classes】目录里,如果没有【classes】目录,服务器会自动帮我们创建,因此,只要是放置在【src】目录中的资源,最后也会被服务器自动放置在【classes】目录中,这样我们可以继续通过ServletContext对象来获取:

ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/classes/database.properties");
        
        Properties prop = new Properties();
        prop.load(in);
        
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);

 

关于web工程下某个web资源在不同位置下的问题:

 

  问题一:我们为什么不能用传统方式,如FileInputStream或者File对象来直接获取web工程中的资源呢?其实也是可以的,但是有个路径的问题,Servlet中方法所需要的路径都是相对于web应用的路径,而传统的FileInputStream等等中方法所需的路径参数都是相对于虚拟机的路径。而又因为我这个web应用是从MyEclipse中的Tomcat里启动的,所以这时候的虚拟机目录其实是Tomcat中的【bin】目录。所以如果想用传统方式读取文件必须每次都将文件放置在Tomcat的【bin】目录下, 这是多么麻烦的事,因此我们开发web工程就应该使用web工程中的方法来读取文件!但是,这却又引出了问题二。。。

  问题二:当我们web工程中有别的非Servlet的类时,比如JavaBean,当JavaBean需要连接数据库时,这就是非Servlet对象读取web工程中的资源文件了,不能用ServletContext来读取,问题一种也说过不能用传统方式如FileInputStream来读取,那么该如何读取呢?

  答案是:类加载器!关于类加载器的学习请好好查阅相关文章,也是很重要的。由于在【src】目录下的Java程序经过编译成字节码class文件,如果要用到这些类,Java虚拟机需要先将这些字节码文件加载到内存中才可以使用,而这个过程就是由类加载器来完成。因此这就有一个知识点,如果我们将某个web资源放置在【src】目录下,因为这是个web工程,服务器会自动将各个字节码文件重新放置在【classes】目录下, 而这个web资源也会重新被服务器放置在【classes】目录下,那么类加载器能加载【classes】目录下所有的字节码文件,同时,同处在这个目录下的web资源也会被类加载器加载进内存,这时我们就可以使用类加载器读取该web资源了。

  例:在【myservlet】的dao包中创建一个Student的JavaBean对象,并在src【目录下】创建一个student的配置文件student.properties,而这个配置文件内容如下图所示:

  

在Student类中,我们需要通过类加载器来获取输入流来读取这个文件:

public class Student {    
    public void getStudent() throws IOException {
        ClassLoader loader = Student.class.getClassLoader();
        InputStream in = loader.getResourceAsStream("student.properties");
        
        Properties prop = new Properties();
        prop.load(in);
        
        String studentName = prop.getProperty("name");
        String studentAge = prop.getProperty("age");
        System.out.println(studentName+":"+studentAge);
    }
}

另外创建一个Servlet作为可以供浏览器访问的对象,在该Servlet中创建Student的示例来获取配置文件中的内容,这样就达到了从非Servlet对象读取web资源内容并向Servlet对象传递数据:

public class ServletDemo3 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Student student = new Student();
        student.getStudent();
    }
}

注意,这种方法只能是web资源放置在【src】目录中才可以使用,如果要读取的web资源是放置在web工程的目录下,使用类加载器也还是无法读取,因为类加载器只能读取类目录下的文件,这时候非Servlet类就无法读取资源文件,只能使用ServletContext来读取了。

  方立勋老师说:“类加载器只能加载【classes】目录下的所有文件一次,这样在服务器运行web工程的过程中,如果我们修改【classes】目录下的student.properties配置文件,则由于类加载器不再加载,因此使用类加载器的方式不能读取修改后的内容”

但是我修改后,还是可以使用类加载器的方式读取classes】目录下修改后的student.properties配置文件,难道是因为JDK7的原因吗?

  不过不管是什么原因,方立勋老师针对他的问题所采取的解决方案还是值得学习的,他采用先用类加载器获取该配置文件的路径,然后再采用传统方式获取这个文件的输入流。所以在Student中的getStudent()方法代码改为:

public class Student {    
    public void getStudent() throws IOException {
        ClassLoader loader = Student.class.getClassLoader();
        URL fileUrl = loader.getResource("student.properties");
        String filePath = fileUrl.getPath();

        FileInputStream fis = new FileInputStream(filePath);
        Properties prop = new Properties();
        prop.load(fis);
        
        String studentName = prop.getProperty("name");
        String studentAge = prop.getProperty("age");
        System.out.println(studentName+":"+studentAge);    
}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值