在Servlet之外访问ServletContext [英] Accessing ServletContext outside of a servlet

查看:76
本文介绍了在Servlet之外访问ServletContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以就Java webapp问题提出建议?

I wonder if anyone can advise on a Java webapp question?

我有一个标准的Java类集合,该类具有设置和获取属性文件值的方法.这些方法在系统范围内使用,并由servlet和非servlet类方法调用.

I have a set standard Java class which has methods to set and get values of a property file. These methods are used system wide and are called by servlets and non-servlet class methods alike.

但是我想做的是使用ServletContextListener全局设置属性文件的路径,而不是对其进行硬编码或将其存储在数据库中.

But what I would like to do is to use a ServletContextListener to set the paths to the property file globally rather than hard code them or store them in the database.

ServletContextListener可以用于通过context.setAttribute("PROP_FILE_PATH","C:\ ...")为Servlet设置全局变量".但是有没有办法在Servlet之外访问这些变量,或者可以在Servlet之外访问ServletContext?

A ServletContextListener can be used to set 'global variables' for the servlets with context.setAttribute("PROP_FILE_PATH", "C:\..."). But is there a way to access these variables outside the servlets or can ServletContext be accessed outside servlets?

由于调用次数众多,我不认为将ServletContext作为参数传递给我必须获取并设置属性文件值的类方法将是一个可行的选择.

I don't think passing the ServletContext as a parameter to the class methods I have to get and set property file values will be a viable option because of the number of calls.

谢谢

马丁

推荐答案

您总是可以将设置存储在与Servlet上下文不同的位置,例如配置类上的一组静态变量.然后ServletContextListener可以在启动时设置这些变量,并且任何其他代码都可以访问这些静态变量,而不管它们是否有权访问ServletContext本身.

You could always store your settings in a different place than the Servlet Context, say a set of static variables on a configuration class. Then the ServletContextListener could set those variables on startup, and any other code can access those statics, regardless of whether they have access to the ServletContext itself or not.

这篇关于在Servlet之外访问ServletContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆