随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

简介:

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

这样通过反射进行方法的调用,当类中需要增加一个或多个方法时,就不需要做多个参数(方法名)的识别判断,且不用将每一个方法都进行一次调用,只需要将获取的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   时间完全不够用啊  阅读(122)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示