Read Properties File in JSP

How to load and read configuration values from a .properties file in a JavaServer Pages (JSP) web application.

In this JavaAnt guide, we cover reading configuration values from .properties files in JSP and Java web applications.

Why Use Properties Files in JSP?

Hardcoding database URLs, API endpoints, or localized messages inside JSP views makes code hard to maintain. A .properties file on the application classpath allows configuration to be changed without editing JSP markup.

Project Structure

Place your configuration file (such as app.properties) in src/main/resources or WEB-INF/classes so it is packaged into the classpath.

app.properties
app.name=JavaAnt Sample Application
app.env=production
database.url=jdbc:mysql://localhost:3306/sampledb

Utility Class

Create a helper class to read the file via the ClassLoader:

ReadPropertiesUtil.java
package com.javaant.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesUtil {
    private static final Properties properties = new Properties();

    static {
        try (InputStream in = ReadPropertiesUtil.class.getClassLoader().getResourceAsStream("app.properties")) {
            if (in != null) {
                properties.load(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String key) {
        return properties.getProperty(key);
    }
}

Accessing Properties in JSP

In your JSP page, import the utility class and display values:

index.jsp
<%@ page import="com.javaant.util.ReadPropertiesUtil" %>
<!DOCTYPE html>
<html>
<head>
    <title><%= ReadPropertiesUtil.getProperty("app.name") %></title>
</head>
<body>
    <h1><%= ReadPropertiesUtil.getProperty("app.name") %></h1>
    <p>Environment: <%= ReadPropertiesUtil.getProperty("app.env") %></p>
</body>
</html>

For modern Java configuration and Android properties handling, see our properties file guide.

About Glenna Babshire29 Articles
Java & libraries writer. Writes the Java tutorials: the language from Java 21 on, encryption, configuration and the libraries around it.