1.创建Servlet对象,通过服务器反射机制创建Servlet对象,第一次请
求时才会创建。(默认)
2,调用Servlet对象的init()方法,初始化Servlet的信息,init()方法只会在创建后被调用一次;
3,响应请求,调用service()或者是doGet(),doPost()方法来处理请求,这些方法是运行的在多线程状态下的。
4, 在长时间没有被调用或者是服务器关闭时,会调用destroy()方法来销毁Servlet对象。
测试案例:
1 package com.damu.servlet; 2 3 import com.damu.dao.UsersDAO; 4 import com.damu.entity.Users; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 import java.util.Date; 13 14 @WebServlet("/addusers") 15 public class UsersAddServlet extends HttpServlet { 16 17 private UsersDAO usersDAO = new UsersDAO(); 18 @Override 19 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 20 this.doPost(req, resp); 21 } 22 23 @Override 24 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 25 // 获取要添加的用户数据 26 String username = req.getParameter("username"); 27 String userpass = req.getParameter("userpass"); 28 String nickname = req.getParameter("nickname"); 29 String age = req.getParameter("age"); 30 String gender = req.getParameter("gender"); 31 String email = req.getParameter("email"); 32 String phone = req.getParameter("phone"); 33 34 // 根据用户数据创建一个用户对象 35 Users user = new Users(username, userpass, nickname, Integer.parseInt(age), gender, email, phone, new Date(), new Date(), new Date(), 0); 36 37 // 将用户对象添加到数据库中 38 user = usersDAO.addUser(user); 39 40 // 查看刚新增的用户数据 41 resp.sendRedirect("/detail?id=" + user.getId()); 42 } 43 }