【问题标题】:Write sitemap.xml to java webapp root directory permission denied将 sitemap.xml 写入 java webapp 根目录权限被拒绝
【发布时间】:2015-01-19 21:17:48
【问题描述】:

我正在尝试使用 sitemapgen4j 库来构建我的站点地图。我在尝试写入根目录时遇到权限问题

https://code.google.com/p/sitemapgen4j/

根上下文文件夹 (/src/main/webapp)

例外

Problem writing sitemap file /sitemap.xml 
java.io.FileNotFoundException
/sitemap.xml (Permission denied)

代码

File directory = new File("/");
WebSitemapGenerator wsg = new WebSitemapGenerator("http://localhost:8080/app", directory);

有人知道怎么做吗?

【问题讨论】:

    标签: java tapestry


    【解决方案1】:

    我创建了一个临时目录来存储站点地图文件,然后在第一次请求时生成它,并为所有后续请求提供相同的版本,因为我的应用程序中的数据一旦启动就不会改变。

    使用临时目录的好处是你肯定可以写入它(至少我是这么认为的)。

    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.charset.Charset;
    import java.io.BufferedReader;
    
    private Path sitemapDirectory;
    
    @RequestMapping("/sitemap.xml")
    public void sitemap(HttpServletResponse response) throws IOException {
        PrintWriter w = response.getWriter();
        boolean isSitemapAlreadyCreated = sitemapDirectory != null;
        if (isSitemapAlreadyCreated) {
            pipeSitemapToResponse(w);
            return;
        }
        sitemapDirectory = Files.createTempDirectory("mySitemap");
        WebSitemapGenerator wsg = new WebSitemapGenerator("http://localhost:8080/app", sitemapDirectory.toFile());
        wsg.addUrl("http://localhost:8080/app/home");
        wsg.write();
        pipeSitemapToResponse(w);
    }
    
    private void pipeSitemapToResponse(PrintWriter w) {
        Path sitemap = Paths.get(sitemapDir.toString(), "sitemap.xml");
        Charset charset = Charset.forName("UTF-8");
        try (BufferedReader reader = Files.newBufferedReader(sitemap, charset)) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                w.write(line);
            }
        } catch (IOException e) {
            logger.error("Failed to read the sitemap file.", e);
        }
    }
    

    此解决方案使用 Spring 请求映射。它还希望将站点地图文件写为sitemap.xml,除非您有超过 50k 个条目,然后您需要阅读有关处理索引文件的 sitemapgen4j 文档并修改此示例。

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2016-06-25
      • 2011-01-16
      相关资源
      最近更新 更多