创建 JavaEE 项目后,定义一个类,实现 Servlet 接口方法为:
1
| public class ServletDemo1 implements Servlet
|
Servlet 的生命周期方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class ServletDemo2 implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { System.out.println("init......."); } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("service......."); } @Override public String getServletInfo() { return null; } @Override public void destroy() { System.out.println("destroy............"); } }
|
Servlet 的实现需要在 web.xml 中配置路径:
1 2 3 4 5 6 7 8
| <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>
|
在 Servlet 3.0 后,可以不用配置 web.xml 文件,配置 Servlet 方法为使用 @WebServlet 注解: