Servlet 反射代替多次继承操作

        我们在使用servlet的时候会频繁的重写doget,dopost之类的方法,在通常情况下我们会把一系列操作方法写到一个类中,比如对用户的操作就写在一个方法中

操作方法:

        1.写一个BaseServlet类 使其继承HttpServlet

        2.重写doPost方法在方法中写入以下代码

        3.对系列操作的类继承BaseServlet

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");

        String action = req.getParameter("method");

        //使用反射执行业务方法
        try {
            //获取方法
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);

            //设置权限 (访问私有)
            method.setAccessible(true);

            //执行方法
            method.invoke(this, req, resp);

        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值