How to serve static resources in a web application
In any web application, there exists a folder named WebContent that automatically holds .class and jar files.
When running a web application in eclipse or when deploying a war file to an external Tomcat, all that Tomcat needs is the WebContent folder.
In this tutorial, we show 2 ways for serving static resources in a web application.
The standard way for defining static resources in a web application is to place them in a custom folder directly under WebContent and beside WEB-INF folders.
Normally we create a folder named ‘static’ and place all resources like (HTML, js, CSS ..) inside it. This folder is automatically exported directly under WebContent when generating a war file or when running the application through eclipse.
In order to use the static resources inside a servlet, you can access them through the root path ‘/’ as the following:
RequestDispatcher view = request.getRequestDispatcher("/static/html/Home.html");
In the above code snippet, we access an html file called Home.html which resides under WebContent/static/html.
We can also define static resources just as we do in a stand-alone application. We create a folder named ‘resources’, place all resources inside it and then add it to the classpath.
The classpath resources are automatically deployed under WEB-INF/classes and can be accessed in a servlet like the following:
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/classes/Home.html");