- Servlet Interface:
- The
Servlet
interface is a fundamental part of servlet technology. It defines methods that all servlets must implement. These methods are invoked by the web container during the servlet’s lifecycle. - Here are the key methods of the
Servlet
interface:init(ServletConfig config)
: Initializes the servlet. It’s called by the web container only once when the servlet is loaded.service(ServletRequest request, ServletResponse response)
: Provides a response for incoming requests. This method is invoked by the web container for each request.destroy()
: Indicates that the servlet is being destroyed. It’s called only once.getServletConfig()
: Returns theServletConfig
object associated with the servlet.getServletInfo()
: Provides information about the servlet (e.g., copyright, version).
- Below is a simple example of a servlet that implements the
Servlet
interface:
- The
import java.io.*;
import javax.servlet.*;
public class First implements Servlet {
ServletConfig config = null;
public void init(ServletConfig config) {
this.config = config;
System.out.println("Servlet is initialized");
}
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<b>Hello, simple servlet!</b>");
out.print("</body></html>");
}
public void destroy() {
System.out.println("Servlet is destroyed");
}
public ServletConfig getServletConfig() {
return config;
}
public String getServletInfo() {
return "Copyright 2007-1010";
}
}
- Steps to Create a Servlet Example:
- To create a servlet, follow these steps:
- Set up your development environment (e.g., using Apache Tomcat).
- Create a Java class that implements the
Servlet
interface (as shown in the example above). - Compile the servlet class.
- Deploy the compiled class file to the servlet container (e.g., Tomcat).
- Access the servlet via a URL (e.g.,
http://localhost:8080/your-web-app/First
).
- To create a servlet, follow these steps: