我想使用一个在部署到Server后只调用一次的方法 [英] I want to use a method which is called only once after deploying to Server

查看:169
本文介绍了我想使用一个在部署到Server后只调用一次的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Servlets的新手。我想使用一个在部署到服务器后只调用一次的方法。我查看了 的HttpServlet#的init() 。但我发现每次请求都会调用它。我误解了吗?有什么替代 init()

I am new to Servlets. I want to use a method which is called only once after deploying to server. I looked at HttpServlet#init(). But I figured out it is called with each request. Did I misunderstand it? What are the alternatives to init()?

推荐答案

不,它不会在每个请求中调用。它仅在servlet初始化期间调用,通常在webapp的生命周期中只发生一次。另请参阅此答案有关如何创建和执行servlet的详细信息。

No, it is not called in each request. It is only called during initialization of the servlet which usually happens only once in webapp's lifetime. Also see this answer for a bit more detail how servlets are created and executed.

如果您确实想要进行一些全局/应用程序范围的初始化(因此本身并不仅限于特定的servlet),那么你通常会使用 ServletContextListener 。您可以在 contextInitialized()方法中执行初始化操作。

If you actually want to do some global/applicationwide initialization (which is thus not per se tied to only the particular servlet), then you would normally use the ServletContextListener for this. You can do the initialization stuff in the contextInitialized() method.

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class Config implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }
    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }
}

如果你不在 Servlet 3.0 尚未升级,因此无法使用 @WebListener 注释,那么您需要在<$中手动注册它c $ c> /WEB-INF/web.xml 如下所示:

If you're not on Servlet 3.0 yet and can't upgrade, and thus can't use @WebListener annotation, then you need to manually register it in /WEB-INF/web.xml like below:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

这篇关于我想使用一个在部署到Server后只调用一次的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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