5/27

清荣峻茂發表於2024-05-27

問題:平常我們編寫servlet的時候,經常會一個java檔案寫一個方法呼叫這樣很麻煩,會寫一堆的Servlet檔案

解決方法:編寫基本的baseservlet,之後其他的檔案採用/Brand/*呼叫該方法,替換HttpServlet,根據請求的最後一段路徑來進行方法分發

BaseServlet.java檔案

package com.hailei.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替換HttpServlet,根據請求的最後一段路徑來進行方法分發
 */

public class BaseServlet extends HttpServlet {

    //根據請求的最後一段路徑來進行方法分發
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 獲取請求路徑
        String uri = req.getRequestURI(); // /brand-case/brand/selectAll

        //2. 獲取最後一段路徑,方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1); //  /selectAll? selectAll?

        //2. 執行方法
        //2.1 獲取BrandServlet /UserServlet 位元組碼物件 Class

        Class<? extends BaseServlet> cls = this.getClass();
        //2.2 獲取方法 Method物件
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //2.3 執行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}

之後,其他的就直接寫後面就行

package com.hailei.web.servlet;


import com.alibaba.fastjson.JSON;
import com.hailei.pojo.Brand;
import com.hailei.pojo.PageBean;
import com.hailei.service.BrandService;
import com.hailei.service.impl.BrandServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
    private BrandService brandService = new BrandServiceImpl();

    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 呼叫service查詢
        List<Brand> brands = brandService.selectAll();

        //2. 轉為JSON
        String jsonString = JSON.toJSONString(brands);
        //3. 寫資料
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
}

優勢:只需要寫一個Servlet就可以了,把方法往裡面堆放就可以了