1.建Web project“2Servlet_Basic”
2.建包com.amaker.servlet
3.建类“ServletBasic.java”
package com.amaker.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //继承HttpServet,doGet alt+/,sysout alt+/ public class ServletBasic extends HttpServlet { /** * */ private static final long serialVersionUID = 3616093822222878695L; public void init() throws ServletException { System.out.println("init"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("servlet"); } public void destroy() { System.out.println("destroy"); } }
4.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>basicservlet</servlet-name> <servlet-class>com.amaker.servlet.ServletBasic</servlet-class> </servlet> <servlet-mapping> <servlet-name>basicservlet</servlet-name> <url-pattern>/servlet/basic</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <login-config> <auth-method>BASIC</auth-method> </login-config> </web-app>
5.MyHtml.html(WebRoot文件夹)
<!DOCTYPE html> <html> <head> <title>MyHtml.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <!--先调用service方法,没有service调用post方法,“method”上有注明--> <form action="/2Servlet_Basic/servlet/basic" method="post"> <input type="submit" value ="click"> </form> </body>
</html>
访问:
按钮进入后发现console
init
servlet
刷新页面 console
init
servlet
servlet
总结:
servlet的生命周期:
(1)加载实例(创建一个servlet实例)
(2)调用init()方法(仅用一次)
(3)调用service方法(每次请求一次,表明多个用户共享一个servlet实例)
(4)调用destory()方法(tomcat销毁时使用)