用ServletContext读取.properties文件
时间: 2024-04-18 07:04:47 浏览: 131
读取properties文件
可以通过以下代码使用ServletContext读取.properties文件:
```java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/read-properties")
public class ReadPropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = getServletContext();
InputStream inputStream = context.getResourceAsStream("/WEB-INF/config.properties");
Properties properties = new Properties();
properties.load(inputStream);
String databaseUrl = properties.getProperty("database.url");
String databaseUsername = properties.getProperty("database.username");
String databasePassword = properties.getProperty("database.password");
response.getWriter().println("Database URL: " + databaseUrl);
response.getWriter().println("Database Username: " + databaseUsername);
response.getWriter().println("Database Password: " + databasePassword);
}
}
```
其中,读取.properties文件的代码是:
```java
ServletContext context = getServletContext();
InputStream inputStream = context.getResourceAsStream("/WEB-INF/config.properties");
Properties properties = new Properties();
properties.load(inputStream);
```
注意,这里的.properties文件需要放在WEB-INF目录下,以保证安全性。
阅读全文