Servlet运行机制

Servlet运行机制
  Servlet 需要继承抽象父类 HttpServlet ,这个类是一个模板设计模式的类,
  其中 service 方法是一个模板方法. 当接收到请求之后容器会自动调用父类的 service()方法.

  当用户发送请求的时候容器调用对应的 servlet 的 service() 这个模板方法,在该方法中判断用户请求的是什么类型,
  根据类型来确定对应的方法 (doXXX()方法). 如果重写service() 模板方法, service()模板方法中的钩子方法将不被调用

Demo: 调用service() 模板方法中的 doGet 和 doPost 方法
  当容器接收到请求之后 调用的是父类的 service 方法-->在该方法中判断请求的类型-->根据类型调用doGet 和 doPost 方法

 1 @SuppressWarnings("serial")
 2 public class EmpServlet extends HttpServlet {
 3     //取得业务层实现类对象
 4     private IEmpService empservice = (IEmpService)ServiceFactory.geiInstance(EmpServiceImpl.class);
 5     //根据编号查询数据
 6     @Override
 7     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 8         String id = req.getParameter("id");
 9         try {
10             System.out.println(empservice.findEmpById(Integer.parseInt(id)));
11         } catch (Exception e) {
12             e.printStackTrace();
13         }
14     }
15     //取得客户端提交的数据
16     @Override
17     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18         req.setCharacterEncoding("utf-8");
19         String name = req.getParameter("username");
20         String pwd = req.getParameter("pwd");
21         System.out.println("用户名是:" + name + ",密码是: " + pwd);
22     }
23 }

客户端数据:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8     <form action="emp" method="POST">
 9         <input type="text" name="username" value="张三">
10         <input type="password" name="pwd" value="1234">
11         <input type="submit" value="提交">
12         <input type="reset" value="重置">
13     </form>
14 </body>
15 </html>

猜你喜欢

转载自www.cnblogs.com/yslf/p/10738399.html