After creating a JavaEE project, define a class and implement the Servlet interface method as:
public class ServletDemo1 implements Servlet
Servlet life cycle methods:
public class ServletDemo2 implements Servlet {
//初始化方法
//在Servlet被创建时执行。只会执行一次
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init.......");
}
//获取ServletConfig对象
//Servlet的配置对象
@Override
public ServletConfig getServletConfig() {
return null;
}
//提供服务方法
//每一次Servlet被访问时,执行。执行多次
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service.......");
}
//获取Servlet的一些信息,版本、作者
@Override
public String getServletInfo() {
return null;
}
//销毁方法
//在服务器正常关闭时执行。执行一次
@Override
public void destroy() {
System.out.println("destroy............");
}
}
The implementation of Servlet needs to configure the path in web.xml:
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>web.servlet.ServletDemo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/demo1</url-pattern>
</servlet-mapping>
After Servlet 3.0, it is not necessary to configure the web.xml file, and the method of configuring the Servlet is to use @WebServlet annotation:
@WebServlet("/demo")