代码:
import javax.servlet.*;
import java.io.*;
public class Test implements Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println("i am init().........");
}
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("i am service().........");
}
public void destroy() {
System.out.println("i am destory().........");
}
public String getServletInfo() {
return "servlet version ";
}
}
错误:
Test.java:4: Test is not abstract and does not override abstract method getServletConfig() in javax.servlet.Servlet
public class Test implements Servlet
^
通常您应该扩展抽象servlet,它具有某些方法的默认实现。
不要从头开始实现Servlet
。
因为当您将implements
子句放在类上时,您必须为该抽象类或接口的所有抽象方法编写代码,其中所有方法都是抽象的,即纯虚拟的。例外可以在Java8接口中提到,某些方法可以有默认实现。
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
...
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
doGet(request, response);
}
...
}
要了解如何创建servlet的更多信息,请参阅技术课程:
所有servlet类都扩展了HttpServlet
抽象类。HttpServlet
通过提供处理HTTP协议的框架,简化了HTTPservlet的编写。因为HttpServlet
是抽象的,所以你的servlet类必须扩展它并覆盖它的至少一个方法。抽象类是一个包含未实现方法的类,它本身不能被实例化。
public class ExampServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
}
}