How to check if the requested file exists in WEB-INF from a Java servlet?

I am writing a filter that redirects a file .jsto the corresponding file .js.gz, if one exists. So foo.js will go to foo.js.gz. The problem is how to check if the corresponding .js.gz file exists in the WEB-INF directory from the servlet?

Currently, if I do

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

I get:

/test.js
false

Even if the file exists.

+4
source share
1 answer

how to check if the corresponding .js.gz file exists in the WEB-INF directory from the servlet?

Use the ServletContext # getRealPath () method .

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");
}

Read more below.

+3
source

All Articles