这里有人知道如何在 tomcat 服务器上加载文件吗? 我们正在使用: Maven、JSF 2、Spring 3、Tomcat 7
我有以下项目结构:
我要加载page.xml文件!
我考虑在服务器的 server.xml 中的 GlobalNamingResource 中设置一个环境变量。但是如何在我的 WebApp 中访问这个变量呢?
或者我可以使用 ContextClassLoader,但如果我想加载那个文件,我总是返回 null。
问题是,我不能使用 FacesContext,因为如果我调用 FacesContext.getCurrentInstance(),我会返回 null;
目前我必须对路径进行硬编码才能使其正常工作。但是如果我想在 eclipse 中测试它或者如果我将它部署在服务器上,我总是必须改变这个路径。
@PostConstruct
public void loadMenu() {
List<Page> pageCollection = new ArrayList<Page>();
Page page = null;
File xmlFile = new File(
"C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps\\rainstar2-webapp\\WEB-INF\\classes\\at\\beko\\rainstar2\\page.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDoc = db.parse(xmlFile);
xmlDoc.getDocumentElement().normalize();
NodeList pages = xmlDoc.getElementsByTagName("page");
int size = pages.getLength();
Node pageNode = null;
for (int i = 0; i < size; i++) {
pageNode = pages.item(i);
NamedNodeMap attr = pageNode.getAttributes();
page = new Page();
page.setLabel(attr.getNamedItem("key").getNodeValue()
.toString());
page.setRedirect(Boolean.valueOf(attr.getNamedItem("redirect")
.getNodeValue().toString()));
page.setNavigationName(attr.getNamedItem("url").getNodeValue()
.toString());
page.addRole(attr.getNamedItem("role").getNodeValue()
.toString());
pageCollection.add(page);
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
最佳答案
对于 JSF,您可以使用 ResourceHandler .它适用于 /webapp/resources
下的资源。我不完全确定 /main
FacesContext currentContext = FacesContext.getCurrentInstance();
ResourceHandler resourceHandler = currentContext.getApplication()
.getResourceHandler();
Resource resource = resourceHandler.createResource(fileName, libraryName);
libraryName
是/webapp/resources
下文件夹的名称。
编辑:在不依赖 JSF 的情况下,您可以使用旧的 ClassLoader。 .
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("/path/to/file/from/.war_as_root/fileName");
请注意,该路径是相对于您打包的 .war 的根目录
关于java - 在 Tomcat 服务器上加载文件(JSF、SPRING),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10829113/