Refused to display '' in a frame because it set 'X-Frame-Options' to 'deny'

前言

當(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è)請求

  1. 前端訪問的時(shí)候, 在請求參數(shù)中添加 method 屬性, 其中值是將要訪問的方法
  2. 在 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();
        }
        
    }
}
  1. 抽取完成后, 業(yè)務(wù) Servlet 的書寫方式變成:

    1. 繼承 BaseServlet
    2. 實(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 {
            // 邏輯代碼
        }
    
    }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容