Image of How to serve static resources in a web application

ADVERTISEMENT

Table of Contents

Introduction

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.

1- WebContent

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");
view.forward(request, response);

In the above code snippet, we access an html file called Home.html which resides under WebContent/static/html.

2- Classpath

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");
view.forward(request, response);

Summary

In this tutorial, we show 2 ways for serving static resources in a web application.

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes