The servlet lifecycle is highly flexible. The only rules that theservlet container must strictly abide by the following lifecycle agreed: □ Generate and initialize the servlet □ Handle Customer Request □ Uninstall the servlet and use unused unit collection
Corresponding to the above agre, we have the following method: □ init () method: responsible for initializing the servlet object □ service () method: responsible for responding to customer request; □ DESTROY () method: When servlet object exits the life cycle, responsible Release occupancy resource;
An instance, counter instance, initialization file: //initcounter.javaimport java.io. *; Import javax.servlet.http. *;
public class InitCounter extends HttpServlet {int count; public void init () throws ServletException {String initial = getInitParameter ( "initial"); try {count = Integer.parseInt (initial);} catch (NumberFormatException e) {count = 0;} } Public void doget (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException {res.setContentType ("text / html"); PrintWriter out = res. max;
Count ; "Since Loading this Servlet Instance Has Been Accessed Count " Times ");} public void destroy () {super.destroy ();}}
File: //web.xml XML Version = "1.0" Encoding = "ISO-8859-1"?>