BaseServlet 继承 httpServlet

BaseServlet   核心

 1 package cn.core;
 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  * 1:继承HttpServlet让它成为Servlet<br>
13  * 2:声明它的抽象的则是指这个类不能配置到web.xml中去<br>
14  */
15 public abstract class BaseServlet extends HttpServlet {
16     /**
17      * 3:直接重写service方法,以避免执行doGet/doPost分支
18      */
19     @Override
20     public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21         // 6:由于所有请求,都是先从这儿过去了,所以可以直接统一的设置请求编码和响应的类型
22         req.setCharacterEncoding("UTF-8");
23         resp.setContentType("text/html;charset=UTF-8");
24         // 7:用户通过参数的形式通知调用哪一个方法?method=add调用add方法
25         // 解析出这个参数
26         String methodName = req.getParameter("method");
27         if (methodName == null || methodName.trim().equals("")) {
28             // 默认为exuecte
29             methodName = "execute";
30         }
31         // 8:再通过反射调用子类方法,可以使用this反射出子类。
32         // 反射出方法
33         try {
34             Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
35             // 执行调用
36             method.invoke(this, req,resp);
37         } catch (Exception e) {
38             throw new RuntimeException(e);
39         }
40 
41     }
42 
43     /**
44      * 4:开发一个默认的方法,如果用户没有指定执行哪一个方法,则默认就执行默认的这个方法
45      * 5:将这个方法修改成抽象的,以避免继承BaseServlet的类忘记开发execute
46      */
47     public abstract void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception;
48 }


方法测试
 1 package cn.examples;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import cn.core.BaseServlet;
 7 
 8 public class PersonServlet extends BaseServlet {
 9     // http://localhost:9999/mvc/person
10     @Override
11     public void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
12         System.err.println("这是默认的execute...");
13     }
14 
15     // http://localhost:9999/mvc/person?method=addPerson
16     public void addPerson(HttpServletRequest req, HttpServletResponse resp) {
17         System.err.println("this is add...");
18     }
19 
20     // http://localhost:9999/mvc/person?method=upload
21     public void upload(HttpServletRequest req, HttpServletResponse resp) {
22         System.err.println("this is upload img...");
23     }
24 
25     // http://localhost:9999/mvc/person?method=del
26     public void del(HttpServletRequest rr, HttpServletResponse resp) {
27         System.err.println("this is delete...");
28     }
29 }
原文地址:https://www.cnblogs.com/fujilong/p/5335763.html