之前发过一篇博客是BaseServlet的使用方法,却没有BaseServlet的代码。这次备上代码,并附上自己对BaseServlet原理的理解。
1.BaseServlet代码,网上有多种版本,原理基本相同,通过传来的method值来判断调用servlet中的那个servlet。
1 package servlet; 2 3 import java.io.IOException; 4 import java.lang.reflect.Method; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 /** 12 * BaseServlet用来作为其它Servlet的父类 13 * 一个类多个请求处理方法,每个请求处理方法的原型与service相同! 原型 = 返回值类型 + 方法名称 + 参数列表 14 */ 15 @SuppressWarnings("serial") 16 public class BaseServlet extends HttpServlet { 17 @Override 18 public void service(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 response.setContentType("text/html;charset=UTF-8");//处理响应编码 21 22 /** 23 * 1. 获取method参数,它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法 24 */ 25 String methodName = request.getParameter("method"); 26 Method method = null; 27 /** 28 * 2. 通过方法名称获取Method对象 29 */ 30 try { 31 method = this.getClass().getMethod(methodName, 32 HttpServletRequest.class, HttpServletResponse.class); 33 } catch (Exception e) { 34 throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", e); 35 } 36 37 /** 38 * 3. 通过method对象来调用它 39 */ 40 try { 41 String result = (String)method.invoke(this, request, response); 42 if(result != null && !result.trim().isEmpty()) {//如果请求处理方法返回不为空 43 int index = result.indexOf(":");//获取第一个冒号的位置 44 if(index == -1) {//如果没有冒号,使用转发 45 request.getRequestDispatcher(result).forward(request, response); 46 } else {//如果存在冒号 47 String start = result.substring(0, index);//分割出前缀 48 String path = result.substring(index + 1);//分割出路径 49 if(start.equals("f")) {//前缀为f表示转发 50 request.getRequestDispatcher(path).forward(request, response); 51 } else if(start.equals("r")) {//前缀为r表示重定向 52 response.sendRedirect(request.getContextPath() + path); 53 } 54 } 55 } 56 } catch (Exception e) { 57 throw new RuntimeException(e); 58 } 59 } 60 }
2.BaseServlet原理
BaseServlet原理:一个servlet只有一个doPost()方法和doGet()方法,我们看过源码就可以知道,是用service方法来调用doxx方法,所以我们重写service()方法就可以实现一个类多个请求处理方法。
Servlet生命周期分为三个阶段:
1,初始化阶段 调用init()方法
2,响应客户请求阶段 调用service()方法
3,终止阶段 调用destroy()方法