BaseServlet的编写使用反射完成servlet后端方法的分发

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {//基类

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {//service完成方法的分发
        //通过基类对所用请求进行格式化
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //处理前端代码乱码
        String mark = req.getParameter("mark");//规定之后所有请求的参数的参数名,?mark=doselect(方法名)
        if (mark==null||mark==""){
            throw  new RuntimeException("此方法名不存在");//为什么使用运行时异常,使用运行时异常不需要抛出异常
        }

        Class cla=this.getClass(); //谁调用我?我代表谁
        //第一个参数是方法名,第二个参数是方法所需要参数的值的class文件
        try {
            Method method = cla.getMethod(mark, HttpServletRequest.class, HttpServletResponse.class);//动态获取参数,和请求对象和响应对象
            method.invoke(this,req,resp);//子类继承这个基类,里面的方法必须是public修饰的方法,如果私有则必须暴力反射解决
            //子类的方法都必须有两个参数,循序分别是HttpServletRequest,HttpServletResponse
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值