BaseServlet method找不到方法的问题

本文介绍了一个Servlet中实现多个请求处理方法的技术方案。通过反射机制,Servlet可以根据不同的请求参数调用相应的处理方法,如addUser和editUser等。文章讨论了如何使用getMethod和getDeclaredMethod来调用不同类型的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在实验一个Servlet有多个请求处理的方法

package com.ymh.servlet;

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.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author cobblepot.ymh on 2017/10/5 下午9:47.
 *
 *  在这里给出多个请求处理的方法,
 *  请求处理方法:除了名称以外,都与service方法相同
 */

@WebServlet("/AServlet")
public class AServlet extends javax.servlet.http.HttpServlet {

    protected void doPost(HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    public void addUser(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("adduser");
    }

    public void editUser(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("edituser");
    }


    protected void service(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String methodName = request.getParameter("method");
        if(methodName == null || methodName.trim().isEmpty()){
            throw new RuntimeException("没有传递参数");
        }

        Class c = this.getClass();
        Method method = null;
        try {
            method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException( methodName + "方法不存在");
        }

        try {
            method.invoke(this, request, response);
        } catch (Exception e) {
            throw new RuntimeException(methodName + "方法不存在");
        }
    }



}

出现了异常
这里写图片描述

里面的c.getMethod()只能找到public的方法
而getDeclaredMethod 可以调用所有方法

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值