简体   繁体   English

java servlet初始化和销毁

[英]java servlets init and destroy

servlets uses init() to initialize servlets status and destroy to clean up. servlet使用init()初始化servlet的状态并销毁以进行清理。 Is there a special class name we need to put init() and destroy()? 我们需要放置init()和destroy()的特殊类名吗? How does servlets know where to find these methods? servlet如何知道在哪里可以找到这些方法?

asp.net has a global.asax to handle similar thing in asp.net , servlets has a special class to do the same thing? asp.net有一个global.asax来处理asp.net中的类似事情,servlet有一个特殊的类来做同样的事情?

Thanks 谢谢

Servlet最终将是javax.servlet.Servlet类的子类,该类定义了这些方法。

It should be in the same class as your Servlet class. 它应该与Servlet类在同一类中。

All servlets inherit this method from the base Servlet class. 所有Servlet都从Servlet基类继承此方法。 Unless you want to do some additional processing, the inherited method should be fine and you dont need to override this method in each of your servlets. 除非您想要进行一些其他处理,否则继承的方法应该没问题,您不需要在每个servlet中都重写此方法。

Servlets are deployed in the Container(Web Server/Application Server),That container will take care of initializing or destroying of servlets,and we dont have predefined classes to initialise and destroy for servlets,if we use particular class that means we are depending on that class(Tightly Coupling) thats not recomended. Servlet部署在容器(Web服务器/应用服务器)中,该容器将负责Servlet的初始化或销毁,如果我们使用特定的类,这意味着我们依赖于Servlet,则我们没有预定义的类来初始化和销毁​​Servlet。该类(紧密耦合)不建议使用。 Now we are using GenericServlet,and HttpServlet classes for that methods..once refer J2EE API and find this classes and methods in them.. 现在,我们正在使用GenericServlet和该方法的HttpServlet类。一旦引用J2EE API并在其中找到此类和方法。

运行Servlet的JVM仅在扩展ServletHttpServlet类中查找这些方法。

Servlets are managed objects. Servlet是托管对象。 This means that they are executed inside a container that manages their lifecycles (instantiates the servlets, call their relevant methods when it is appropiate, and releases them). 这意味着它们在管理其生命周期的容器中执行(实例化servlet,在适当时调用它们的相关方法,然后释放它们)。 The container (Tomcat, Glassfish, ...) knows when to call these methods at the right time because it is implemented that way, there is nothing special about that. 容器(Tomcat,Glassfish等)知道何时在正确的时间调用这些方法,因为它是通过这种方式实现的,对此没有什么特别的。

If the container had a bug, it could even call, say, destroy() at init time and init() at destroy time. 如果容器有错误,它甚至可以在初始化时调用destroy(),在破坏时调用init()。 That bug would be fixed quickly, though. 但是,该错误会很快得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM