本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

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();
        }
    }
}
# JavaWeb  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×