Can we call destroy() method inside the init() method? What
happens when we do so?
Answer Posted / suraj kumar
This action does not disturb the normal life cycle flow of the servlet. The servlet will work normal. You may test the below code.
/**
* @author Suraj
*
*/
public class TestServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException{
super.init(config);
destroy();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("I am test servlet.");
}
}
Web.xml
--------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Servlet</display-name>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.esspl.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
------------------------------------
Test URL: http://<HOST>:<PORT>/<Context>/TestServlet.do
| Is This Answer Correct ? | 10 Yes | 4 No |
Post New Answer View All Answers
What is servlet mapping?
Why do we need servlet filter?
What are the advantages of Servlet over CGI?
What are common tasks performed by Servlet Container?
What are different methods of session management in servlets?
What is ServletConfig object?
What is session tracking?
What is the use of servlet wrapper classes?
What are the differences between the servletconfig interface and the servletcontext interface?
Which exception is thrown if the servlet is not initialized properly?
What do you mean by singlethreadmodel interface?
Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?
Which method of the httpservletrequest object is used?
Why is a constructor needed in a servlet even if we use the init method?
What are all the protocols supported by httpservlet?