Why there are no constructor in servlet?

孤街醉人 提交于 2020-01-03 01:49:09

问题


I am studying servlets I read that servlets are java programs but there are no constructor in servlet... Can anybody elaborate on it?


回答1:


There are as in any other java class, but you don't need to invoke it. The webcontainer will call it for you.

Most servlets do not hold instance data, hence, most of adding code in the constructor doesn't make any sense.




回答2:


If you need to initialize your servlet you'll have to override the init method.




回答3:


There is a constructor in servlet (take a look at HttpServlet, for example), but usually the web container will take care of calling it for you.

However, when you are implementing a servlet, you normally are concerned with just overriding the doGet() and doPost() method (or the service() method, if you are working with other than HttpServlet)




回答4:


Ya we can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose but this type of approch is not so common.You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet servlet container is responsible for instentiating the servlet so the constructor is also called by servlet container only.




回答5:


Yes definitely we can have a constructor inside the servlet but the only one disadvantage when we define a Constructor servlet cannot get the initial parameters and hence we use init() method to initialize a servlet.



来源:https://stackoverflow.com/questions/2103479/why-there-are-no-constructor-in-servlet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!