java - 从 JSP 中的属性目录获取文本文件

标签 java jsp servlets

我有:

名为 index.jsp 的 JSP 文件,其中包含以下代码:

<%
    JSONVerschillendeTalen jsonVerschillendeTalen = JSONVerschillendeTalen.getInstance();
    JSONObject algemeenJSON = null;
    JSONObject indexJSON = null;
    try {
        indexJSON = jsonVerschillendeTalen.getJSONObject(request, "Index.txt");
        algemeenJSON = jsonVerschillendeTalen.getJSONObject(request, "Algemeen.txt");
    } catch (ParseException e) {
        e.printStackTrace();
    }
%>

还有一个名为 JSONVerschillendeTalen 的类,其中包含以下代码:

public class JSONVerschillendeTalen {

    private static JSONVerschillendeTalen jsonVerschillendeTalen = new JSONVerschillendeTalen();
    private JSONParser jsonParser = new JSONParser();

    public static JSONVerschillendeTalen getInstance() {
        return jsonVerschillendeTalen;
    }

    public JSONObject getJSONObject(HttpServletRequest req, String bestandsnaam) throws IOException, ParseException {
        return (JSONObject) jsonParser.parse(new FileReader(getClass().getClassLoader()
            .getResource("NL/" + bestandsnaam).getPath().replaceAll("%20", " ")));
    }

    private JSONVerschillendeTalen() {

    }

}

每当我在普通类中运行 index.jsp 文件中的代码(用于测试)时,它都会起作用。当我在 jsp 文件中运行相同的代码时,却没有。有谁知道为什么吗?

Properties directory

最佳答案

尝试使用getClass().getResource()而不是getClass()。 getClassLoader().getResource()。第二种方法相对于 ClassLoader 根搜索资源,这很可能与 Web 容器中的源目录不同。

已关注 answer对两者之间的差异有很好的解释。

关于java - 从 JSP 中的属性目录获取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570744/

相关文章:

java - 忽略正则表达式术语的拆分?

apache - 设置 Tomcat 以处理 DocumentRoot 中的 JSP

java - 已为此响应调用 getOutputStream()

java - 从 html 文件读取 json 数组并在 servlet 中打印值

java - Jfreechart:如何制作 x 轴为字符串、y 轴为整数的直方图?

java - 在 Quartz 中使用 property/xml 文件动态添加脚本作为作业

java - 使用 DashO 进行 war 混淆

java - 无法从 url.getFile() 获取文件

java - 如何通过JSON获取特定格式的数据

java - 删除ArrayList中的对象本身