サーブレット コンテキストの初期化フェーズで servletContext.setAttributes を使用して、いくつかのアプリケーション全体の変数を設定したいと考えています。これを実現するにはどうすればよいですか。
5277 次
2 に答える
1
ロジックをサーブレットに近づけたい (リスナーを使用しない) 場合は、サーブレットinit
メソッドをオーバーライドできます。そのようです:
@Override
public void init() throws ServletException {
ServletContext sc = getServletContext();
// Store our attribute(s)!
// Check first to make sure it hasn't already been set by another Servlet instance.
if (sc.getAttribute("key") == null)
sc.setAttribute("key", "value");
}
また、 に電話する必要はありませんsuper.init(config)
。ドキュメントを参照してください。
于 2013-02-12T17:47:32.057 に答える
1
の初期化javax.servlet.SevletContextListener
時にコールバックを取得する実装。javax.servlet.ServletContext
次に例を示します。
public class MyServletContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent sce)
{
ServletContext sc = sce.getServletContext();
//do your initialization here.
sc.setAttribute(.....);
}
public void contextDestroyed(ServletContextEvent sce)
{
ServletContext sc = sce.getServletContext();
//do your cleanup here
}
}
于 2012-07-05T05:38:38.390 に答える