如何从Java Servlet中检查是否存在于WEB-INF的请求文件?

5

我正在编写一个过滤器,如果存在对应的.js.gz文件,就将.js文件重定向到它的相应.js.gz文件。所以如果有foo.js文件,就会重定向到foo.js.gz。问题是,如何从servlet中检查WEB-INF目录中是否存在相应的.js.gz文件?

目前,如果我执行以下操作

System.out.println(httpServletRequest.getRequestURI());
File f = new File( httpServletRequest.getRequestURI() ); 
System.out.println( f.exists);

我收到:

/test.js
false

即使文件存在。

1个回答

4

如何从servlet中检查WEB-INF目录中是否存在对应的.js.gz文件?

使用ServletContext#getRealPath()方法。

File file = new File(request.getServletContext().getRealPath("/WEB-INF/foo.js.gz"));
System.out.println(file.getAbsolutePath());
if(file.exists()){
    System.out.println("file exists");
}

欲了解更多信息,请阅读下方的评论。


似乎我不需要指定/WEB-INF,只需执行String path = request.getServletContext().getRealPath( request.getRequestURI() ); File f = new File(path);即可得到正确的结果。 - Ali
request.getRequestURI() 给出类似于 /foo.js 的东西。 - Ali
在您的端上进行测试,并在文件名末尾添加“.gz”。 - Braj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接