I'd like to know if anyone has a solution to access resources of a website through a servlet only. I have all my resources under WEB-INF. In other words, I don't want users to have direct access to any of my resources.
You can use ServletContext#getResource()
for that.
URL resource = getServletContext().getResource("/WEB-INF/file.ext");
File file = new File(resource.getPath());
// ...
You can even use ServletContext#getResourceAsStream()
to get an InputStream
directly:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.ext");
// ...
As you can see in the examples, the ServletContext
is available in servlets by the inherited GenericServlet#getServletContext()
method.
That said, the phrase I don't want users to have direct access to any of my resources. is a bit contradicting. You're serving those resources by a servlet anyway? A servlet is directly accessible by URL. How is that different from "direct access"? Or do you just want to control the access based on some conditions? I'd say, a Filter
is more suitable for this task.
Usually one would only fully hide the JSP files from direct access. In a Servlet which acts as front controller (according the MVC pattern) you could then forward requests to JSP files using RequestDispatcher#forward()
which you in turn can obtain by ServletRequest#getRequestDispatcher()
.
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
You can hide jsp from the end user. In fact, you don't even have to deploy original jsp files with your web application, you can precompile them:
http://tomcat.apache.org/tomcat-5.5-doc/jasper-howto.html#Web%20Application%20Compilation
And the only way to hide html/js/css files is not to use them. Anything that's sent to the browser can be viewed there.