zoukankan      html  css  js  c++  java
  • Servlet和模本办法

       抽象类HttpServlet,提供7个子方法的默认实现,当我们手写Servlet只需要继承HttpServlet并替换相应的do方法来完成自己的业务逻辑即可。

             我们一般的实现方法:

    [java] view plain copy
     
    1. public MyServlet extends HttpServlet{  
    2.     public void doGet(HttpServletRequestrequest, HttpServletResponse response){  
    3.     // 处理  
    4. }  
    5.     public void doPost()HttpServletRequestrequest, HttpServletResponse response){  
    6.     // 不关心get、post请求,因此post处理直接调用get处理  
    7.     doGet(request, response);  
    8. }  
    9. }  



             Servlet之所以牵扯到了模版方法模式,由于Servlet中最重要的service方法,所有的请求,都先到达service。它定义了HttpServlet处理的总流程和框架。

             Service代码

    [java] view plain copy
     
    1. 1.   public void service(ServletRequest req, ServletResponse res)    
    2. 2.      throws ServletException, IOException    
    3. 3.    {    
    4. 4.      HttpServletRequest request;    
    5. 5.      HttpServletResponse response;    
    6. 6.      try    
    7. 7.      {    
    8. 8.        request = (HttpServletRequest)req;    
    9. 9.        response = (HttpServletResponse)res;    
    10. 10.     } catch (ClassCastException e) {    
    11. 11.       throw new ServletException("non-HTTP request or response");    
    12. 12.     }    
    13. 13.     //调用protected service    
    14. 14.     service(request, response);    

             这里顺便提一下模版方法模式:定义一个操作中的算法的骨架,而将一些可变部分的实现延迟到子类中。模版方法模式使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定的步骤。 

  • 相关阅读:
    HTML介绍
    python D41 前端初识
    mysql索引原理与查询优化
    python D41
    python D40 pymsql和navicat
    python D40 以及多表查询
    python D35 selectors模块
    python D35 I/O阻塞模型
    测试过程
    测试基础
  • 原文地址:https://www.cnblogs.com/writeLessDoMore/p/6798930.html
Copyright © 2011-2022 走看看