随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

简介:

获取浏览器发送的参数,然后通过反射获取接收参数的对应方法;

这样通过反射进行方法的调用,当类中需要增加一个或多个方法时,就不需要做多个参数(方法名)的识别判断,且不用将每一个方法都进行一次调用,只需要将获取的Method使用invoke()调用即可,大大地减少了重复操作。

代码:

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

/**
 * 在这里给出多个请求处理方法 请求处理方法:除了名称以外,都与service方法相同
 * 
 * @author CDU_LM
 *
 */
@WebServlet("/AServlet")
public class AServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 获取参数识别用户想要求情的方法 然后判断并调用对应的方法
         */
        String methodName = req.getParameter("methodName");
        if (methodName == null || methodName.trim().isEmpty()) {
            throw new RuntimeException("没有传递参数");
        }// 获取当前类class对象
        Class<? extends AServlet> clazz = this.getClass();
        // 设置接收方法的参数
        Method method = null;    
        try {
            // 获取对应方法,传入方法名和参数类型的class
            method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            throw new RuntimeException("调用 " + methodName + " 方法不存在!!");
        }
        // 调用方法
        try {
            // 调用invoke()执行方法,
            method.invoke(this, req, resp);
        } catch (Exception e) {
            System.out.println("调用" + methodName + "方法失败!!");
            throw new RuntimeException(e);
        }
    }

    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-------- addUser() --------");
        resp.getWriter().print("-------- addUser() --------");
    }

    public void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-------- modifyUser() --------");
        resp.getWriter().print("-------- modifyUser() --------");

    }

    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-------- deleteUser() --------");
        resp.getWriter().print("-------- deleteUser() --------");
    }

}

浏览器请求:

控制台输出:

这样就通过传入的参数(方法名称)进行反射调用。

 

posted on 2022-04-11 15:12  时间完全不够用啊  阅读(103)  评论(0编辑  收藏  举报