📜  Servlet接口

📅  最后修改于: 2021-01-09 12:27:20             🧑  作者: Mango

Servlet接口

Servlet接口提供了所有servlet的通用行为。Servlet接口定义了所有servlet必须实现的方法。

需要为创建任何Servlet(直接或间接)创建Servlet接口。它提供了3种生命周期方法,用于初始化servlet,服务请求和销毁servlet,以及2种非生命周期方法。

Servlet接口的方法

Servlet接口中有5种方法。初始化,服务和销毁是Servlet的生命周期方法。这些由Web容器调用。

Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.
public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer, copyright, version etc.

通过实现Servlet接口的Servlet示例

通过实现servlet接口,让我们看一下servlet的简单示例。

如果在访问了创建servlet的步骤之后学习了它,那就更好了。

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("");
out.print("hello simple servlet");
out.print("");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

}