在我的应用程序中,我有一些参数(字符串)我想在服务器之间进行更改。
例如,其中一个参数是一个是/否值,表明服务器是否为生产环境。另一个是运行应用程序的特定机器中给定资源的文件路径。等等
我想将这些值保存在我的 Jetty 网络服务器目录结构中的单独配置文件(纯文本、xml、JSON 或其他简单格式)中。
有没有一种方法可以实现这一点,允许通过键从我的 servlet 中简单地检索字符串值,而无需安装额外的软件或配置复杂的 Jetty 选项?我真的很想避免只需要检索两个或三个值的复杂情况。
编辑: 我是直接使用servlet,没有任何额外的web框架,没有Spring等。软件是用Scala编码的。
JNDI 可能会满足我的需要,但我想要更简单的设置。
我想我正在寻找类似 ServletConfig 的东西,但在服务器级别,而不是网络应用程序级别。
最佳答案
这是一个简单的例子。
在您的 jetty-distribution 目录中,您有一个 /resources/
目录(通过在 /start.ini
文件)
如果您使用以下内容创建 /resources/myconfig.properties
(例如):
food=fruit
fruit.color=yellow
fruit.name=banana
然后你可以让一个 Servlet 像这样在 init() 上加载它:
public class LoadResourceServlet extends HttpServlet
{
private Properties props;
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
props = new Properties();
URL url = this.getClass().getResource("/myconfig.properties");
if (url != null)
{
try (InputStream stream = url.openStream())
{
props.load(stream);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/plain");
try (PrintWriter writer = resp.getWriter())
{
writer.printf("food = %s%n",props.getProperty("food"));
writer.printf("fruit.color = %s%n",props.getProperty("fruit.color"));
writer.printf("fruit.name = %s%n",props.getProperty("fruit.name"));
}
}
}
关于java - Jetty 用户自定义配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122700/