久久久久久AV无码免费看大片,亚洲一区精品人人爽人人躁,国产成人片无码免费爱线观看,亚洲AV成人无码精品网站,为什么晚上搞的时候要盖被子

通過類的反射機制及invoke方法實現(xiàn)Servlet來處理多個請求

時間:2021-05-14 17:24:58 類型:JAVA
字號:    

當(dāng)瀏覽器發(fā)送了一次請求到服務(wù)器時,servlet容器會根據(jù)請求的url-pattern找到對應(yīng)的Servlet類,執(zhí)行對應(yīng)的doPost或doGet方法,再將響應(yīng)信息返回給瀏覽器,這種情況下,一個Servlet類,一對配置信息。多個業(yè)務(wù), 就需要多個Servert類, 效率太低下,  實際上我們是可以通過一個Servlet類實現(xiàn)多個業(yè)務(wù)請求的


這里通過類的反射機制及invoke方法來實現(xiàn)一Servlet類多請求的操作實例

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

@WebServlet(name = "ServletDoMore", value = "/domore/*")
public class ServletDoMore extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 獲取請求的URI地址信息
        String url = request.getRequestURI();
        // 截取其中的方法名
        String methodName = url.substring(url.lastIndexOf("/")+1);
        System.out.println(methodName);
            // 使用反射機制獲取在本類中聲明了的方法
        Method method = null;
        try {
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            System.out.println("方法不存在");
        }

    }
    private void add(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{
        System.out.println("添加表單");
    }
    private void addsave(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{
        System.out.println("信息保存");
    }
    private void update(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{
        System.out.println("修改表單");
    }
    private void updatesave(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{
        System.out.println("修改保存");
    }
    private void index(HttpServletRequest request, HttpServletResponse respons)throws ServletException, IOException{
        System.out.println("信息列表");
    }
}

請求不同的地址如下就會訪問對應(yīng)的方法

http://localhost/domore/add
http://localhost/domore/addsave
http://localhost/domore/update
http://localhost/domore/updatesave
http://localhost/domore/index


<