Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

servlets

I'm writing a filter which redirects a .js file to its corresponding .js.gz file, if it exists. So foo.js would go to foo.js.gz. The problem is, how do I 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 when the file exists.

like image 644
Ali Avatar asked Oct 01 '22 07:10

Ali


1 Answers

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

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

For more info read comments below.

like image 164
Braj Avatar answered Oct 02 '22 20:10

Braj