Servlet Lifecycle Methods
Sun Nov 03 2024 18:30:17 GMT+0000 (Coordinated Universal Time)
Saved by @signup_returns #html
//Servlet Lifecycle Methods
//input.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Servlet Lifecycle Example</title>
</head>
<body>
<h2>Welcome to the Servlet Lifecycle Example</h2>
<form action="ServletLifecycleExample1" method="post">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
//ServletLifecycleExample1.java
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/ServletLifecycleExample1")
public class ServletLifecycleExample1 extends HttpServlet {
private static final long serialVersionUID = 1L;
private int requestCount;
// Constructor (optional)
public ServletLifecycleExample1() {
super();
System.out.println("Servlet Constructor is called.");
}
// Initialization (called once when the servlet is first loaded)
@Override
public void init() throws ServletException {
requestCount = 0; // Initialize the request counter
System.out.println("init() method called.");
}
// Service method (called for each client request)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestCount++; // Increment the request counter
// Log the request count
System.out.println("service() method called. Request count: " + requestCount);
// Set content type for response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Respond to the client
out.println("<html><body>");
out.println("<h1>Hello, " + request.getParameter("name") + "!</h1>");
out.println("<p>This servlet has served " + requestCount + " request(s).</p>");
out.println("</body></html>");
}
// Destruction (called once before the servlet is destroyed)
@Override
public void destroy() {
System.out.println("destroy() method called.");
}
}



Comments