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.name=JavaAnt Sample Application
app.env=production
database.url=jdbc:mysql://localhost:3306/sampledbUtility Class
Create a helper class to read the file via the ClassLoader:
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:
<%@ 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.