Back to Java
2026-04-145 min read

Add Global Static Files (Java)

Learn Add Global Static Files (Java) step by step with clear examples and exercises.

Why This Matters

In web development, managing static files like CSS, JavaScript, and images is crucial for building efficient and maintainable applications. By adding global static files in a Java web application using Maven, developers can ensure consistency across multiple pages or applications while reducing redundancy and improving performance.

Prerequisites

Before diving into adding global static files, you should have a basic understanding of:

  1. Java programming language (Java SE 8 or later is recommended)
  2. Maven build tool (Maven setup and configuration)
  3. Web application structure (Webapp folder, WEB-INF, web.xml)
  4. Servlets (basic understanding)
  5. HTML, CSS, and JavaScript (familiarity with these technologies is helpful for creating static files)
  6. Understanding of the Maven project structure, including src/main/java, src/main/resources, and src/main/webapp directories.
  7. Familiarity with Maven dependencies and their configuration in the pom.xml file.
  8. Knowledge of how to compile and run a Maven project.

Core Concept

To add global static files in a Java web application using Maven, follow these steps:

  1. Create or navigate to your project's root directory containing the pom.xml file.
  2. In the pom.xml, add the following dependencies under the `` tag:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
  1. Create a new folder named static under the src/main/webapp directory. This is where you'll place your global static files.
  1. To serve these static files, create a simple servlet that forwards requests to the static resources:
package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class StaticResourceServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getPathInfo();
File file = new File(getServletContext().getRealPath("/") + "static" + path);

if (file.exists() && !file.isDirectory()) {
resp.setContentType(getServletContext().getMimeType(file.getName()));
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[4096];
int read;
while ((read = bis.read(buffer)) != -1) {
resp.getOutputStream().write(buffer, 0, read);
}
bis.close();
} else {
req.getRequestDispatcher("/WEB-INF/error.jsp").forward(req, resp);
}
}
}
  1. Register the servlet in the web.xml file:
<servlet>
<servlet-name>StaticResourceServlet</servlet-name>
<servlet-class>com.example.StaticResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StaticResourceServlet</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
  1. Compile and run your Maven project, and you should now be able to access global static files at http://localhost:8080/your-app-name/static/your-file.ext.

Servlet Configuration

Make sure that the servlet is included in the Maven build process by adding it as a source root and specifying its package in the ` section of your pom.xml`. This ensures that the servlet class gets compiled during the build process:

<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<outputDirectory>target/classes</outputDirectory>
<resources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

Worked Example

Let's create a simple example by adding a global CSS file (styles.css) in the src/main/webapp/static directory and using it in an HTML file (index.html):

  1. Create a new folder named static under the src/main/webapp directory if it doesn't exist.
  2. Inside the static folder, create a new file called styles.css:
body {
background-color: #f0f8ff;
}
  1. In the src/main/webapp directory, create a new file called index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Global Static File Example</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<h1>Welcome to our web application!</h1>
</body>
</html>
  1. Run your Maven project, and you should see the CSS applied when accessing http://localhost:8080.

Common Mistakes

1. Forgetting to include the servlet in web.xml

Ensure that the StaticResourceServlet is registered in the web.xml file as shown in the Core Concept section.

2. Incorrect URL pattern

Make sure you use the correct URL pattern (/static/*) in your servlet-mapping.

3. Servlet misconfiguration

Check that your servlet class (StaticResourceServlet) is correctly defined and imported. Also, ensure it extends javax.servlet.http.HttpServlet.

4. File not found exception

Ensure that the static files are placed in the correct location (i.e., under src/main/webapp/static). If a file cannot be found, the servlet will forward the request to an error page specified in your web application's configuration (usually WEB-INF/error.jsp).

5. Servlet not being compiled

Make sure that the servlet is included in the Maven build process by adding it as a source root and specifying its package in the ` section of your pom.xml`.

6. Servlet classpath issue

If you encounter an error related to the servlet class not being found, check that the servlet class is located within the correct package (as specified in the ` tag in the pom.xml`) and that it has been compiled during the Maven build process.

Practice Questions

  1. How can you add a global JavaScript file to your Java web application using Maven?
  2. What should be the URL pattern for accessing static files served by the StaticResourceServlet?
  3. Explain how the getRealPath() method is used in the StaticResourceServlet.
  4. What is the purpose of the BufferedInputStream class in the StaticResourceServlet?
  5. Why is it necessary to set the servlet's scope as provided in the pom.xml file?

FAQ

Q: How can I add a global JavaScript file to my Java web application using Maven?

A: You can create a new JavaScript file in the src/main/webapp/static directory, and include it in an HTML file as shown in the Worked Example section. The servlet (StaticResourceServlet) will handle serving the JavaScript file.

Q: What should be the URL pattern for accessing static files served by the StaticResourceServlet?

A: Use /static/* as the URL pattern to access static files served by the StaticResourceServlet.

Q: Explain how the getRealPath() method is used in the StaticResourceServlet.

A: The getRealPath() method returns the real (absolute) filesystem path of a resource relative to the web application's root directory. In this case, it helps the servlet locate the static file on the filesystem and serve it to the client.

Q: What is the purpose of the BufferedInputStream class in the StaticResourceServlet?

A: The BufferedInputStream class is used to read input data from a file in a buffered manner, which can improve performance by reducing disk I/O operations and network latency. In this case, it helps the servlet read the static file and send its content to the client more efficiently.

Q: Why is it necessary to set the servlet's scope as provided in the pom.xml file?

A: Setting the servlet's scope to provided indicates that the servlet API is provided by the container (e.g., Tomcat), and thus it does not need to be included in the project's distribution. This helps avoid duplicate dependencies when deploying the application.

Add Global Static Files (Java) | Java | XQA Learn