ServletLifeCycleMethods

PHOTO EMBED

Sun Nov 03 2024 11:21:15 GMT+0000 (Coordinated Universal Time)

Saved by @signup1

//Servlet Class
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Annotate the servlet with a URL pattern
@WebServlet("/lifecycle")
public class ServletLifeCycleExample extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // Constructor
    public ServletLifeCycleExample() {
        System.out.println("Constructor called: Servlet instance created.");
    }

    // init method called once when the servlet is loaded
    @Override
    public void init() throws ServletException {
        System.out.println("Init method called: Servlet initialized.");
    }

    // service method called for each request
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Service method called: Handling request.");

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // Write response to client
        out.println("<html><body>");
        out.println("<h1>Servlet Lifecycle Example</h1>");
        out.println("<p>This is a response from the service method.</p>");
        out.println("</body></html>");
        
        out.close();
    }

    // destroy method called once when the servlet is taken out of service
    @Override
    public void destroy() {
        System.out.println("Destroy method called: Servlet is being destroyed.");
    }
} 

//web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>lifecycleServlet</servlet-name>
        <servlet-class>ServletLifeCycleExample</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>lifecycleServlet</servlet-name>
        <url-pattern>/lifecycle</url-pattern>
    </servlet-mapping>
</web-app>


//OUTPUT
Constructor called: Servlet instance created.
Init method called: Servlet initialized.
Service method called: Handling request.
Destroy method called: Servlet is being destroyed.
content_copyCOPY