这里有人知道如何在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根目录开始的相对路径

09-10 12:22
查看更多