代码之家  ›  专栏  ›  技术社区  ›  Mike

在Java Web项目中构建文件路径

  •  0
  • Mike  · 技术社区  · 13 年前

    我正在使用以下代码将css文件动态添加到我的web项目中。然而,当我写出css文件的绝对路径时,它会返回web项目之外的内容。例如,为了进行测试,我在cssAssetsArrayList中添加了css/style.css。当我检查 f.isFile() ,上面写着 home/*username*/css/styles.css 而不是从index.jsp文件到css目录的相对路径。它应该会 workspace/projectName/WebContent/css/styles.css 。如有任何帮助,不胜感激。

    public String buildHead()
    {
        htmlHead = new StringBuilder();
        htmlHead.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        htmlHead.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
        htmlHead.append("<meta http-equiv=\"cache-control\" content=\"max-age=0\" />");
        htmlHead.append("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
        htmlHead.append("<meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" />");
        htmlHead.append("<meta http-equiv=\"pragma\" content=\"no-cache\" />");
        if (this.title.length() > 0)
            htmlHead.append("<title>" + this.title + "</title>");
        else
            htmlHead.append("<title>MMJ Ceo </title>");
    
        for (String css : this.cssAssets)
        {
            File f = new File(css);
    
            if (f.isFile())
            {
                htmlHead.append("<link rel='stylesheet' href=\"" + css + "\"/>");
            }
            else
                return f.getAbsolutePath();
        }
        for(String js : this.jsAssets)
        {
            File f = new File(js);
            if(f.isFile())
                htmlHead.append("<script type='text/javascript' src='" + js + "'></script>");
        }
        htmlHead.append("</head>");
        return htmlHead.toString();
    }
    

    使现代化

    这个代码片段来自我位于projectName.src.com.projectName.view中的Page类,css文件位于projectName/WebContent/css/style.css中,它是从projectName/Web Content/index.jsp调用的

    1 回复  |  直到 13 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    Q: 您正在使用什么IDE?这听起来像Eclipse,在这种情况下,“是的:您应该将css/目录放在“WebContent/”下(就像您的“index.jsp”也在“WebContent/”下一样)。

    …但是。。。。

    正在运行的servlet的根路径是 不同的 从web服务器上的实际物理路径。看这里: