JavaWeb(4)之读取Web应用中的资源

JavaWeb(4)之读取Web应用中的资源

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

现有如下结构的工程:
image.png
如果想要在 Servlet 中读取 test.properties,有通过如下三种方式:

package com.zze.servlet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class TestServletBak extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        func1();
        func2();
        func3();
    }

    private void func1() {
        try {
            ServletContext servletContext = getServletContext();
            // 参数传入相对路径:相对工程部署在 tomcat 下的工程根目录
            InputStream inputStream = servletContext.getResourceAsStream("file/test.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            String name = properties.getProperty("name");
            System.out.println(String.format("from func1:%s", name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void func2() {
        try {
            ServletContext servletContext = getServletContext();
            // 参数传入相对路径:相对工程部署在 tomcat 下的工程根目录
            String realPath = servletContext.getRealPath("file/test.properties");
            FileInputStream inputStream = new FileInputStream(realPath);
            Properties properties = new Properties();
            properties.load(inputStream);
            String name = properties.getProperty("name");
            System.out.println(String.format("from func2:%s", name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void func3() {
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("../../file/test.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            String name = properties.getProperty("name");
            System.out.println(String.format("from func3:%s", name));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/javaweb4.html

Buy me a cup of coffee ☕.