我有:
名为 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 文件中运行相同的代码时,却没有。有谁知道为什么吗?
最佳答案
尝试使用getClass().getResource()
而不是getClass()。 getClassLoader().getResource()
。第二种方法相对于 ClassLoader
根搜索资源,这很可能与 Web 容器中的源目录不同。
已关注 answer对两者之间的差异有很好的解释。
关于java - 从 JSP 中的属性目录获取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570744/