前言
當(dāng)瀏覽器發(fā)送?次請求到服務(wù)器時(shí),Servlet容器會(huì)根據(jù)請求的url-pattern找到對應(yīng)的Servlet類,執(zhí)?對應(yīng)的doPost或doGet?法,最后將響
應(yīng)信息返回給瀏覽器。
這種情況下,?個(gè)具體的Servlet類只能處理對應(yīng)的web.xml中配置的url-pattern請求,?個(gè)Servlet類,?對配置信息。如果業(yè)務(wù)擴(kuò)展,需要三個(gè)Servlet來處理請求,就需要再加上兩個(gè)具體的Servlet類,兩對配置信息,一方面每新增一個(gè)接口都需要增加大量的代碼,另一方面同一個(gè)Model的不同操作方法非常分散;
針對上面提到的問題,我們能不能實(shí)現(xiàn)?個(gè)Servlet處理多個(gè)請求呢?如SpringMVC的Controller。
Servlet 的抽取
使一個(gè) servlet 能接收并處理多個(gè)請求
- 前端訪問的時(shí)候, 在請求參數(shù)中添加 method 屬性, 其中值是將要訪問的方法
- 在 BaseServlet 中利用反射機(jī)制, 根據(jù) method 的值, 調(diào)用對應(yīng)的方法
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
try {
//1、獲得請求的method的名稱
String methodName = req.getParameter("method");
//2、獲得當(dāng)前被訪問的對象的字節(jié)碼對象
Class clazz = this.getClass();//ProductServlet.class ---- UserServlet.class
//3、獲得當(dāng)前字節(jié)碼對象的中的指定方法
Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
//4、執(zhí)行相應(yīng)功能方法
method.invoke(this, req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
-
抽取完成后, 業(yè)務(wù) Servlet 的書寫方式變成:
- 繼承 BaseServlet
- 實(shí)現(xiàn)業(yè)務(wù)方法
public class PrdocutServlet extends BaseServlet { //刪除一個(gè)商品 public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 刪除一個(gè)商品的邏輯 } //根據(jù)商品的類別獲得商品的列表 public void productList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 邏輯代碼 } }