如何利用反射简化Servlet操作

如何利用反射简化Servlet操作

 

一、反射的实现

  新建类BaseServlet,继承HttpServlet(不需要在web.xml文件中配置

  1、在doPost()方法中处理请求乱码,并调用doGet()方法

    //处理post请求乱码,只需要在getParamter方法第一次调用前,设置request的编码
      request.setCharacterEncoding("utf-8");

      调用doGet()

  2、doGet()中:

    //获取用户传递的请求参数
      String methodName = request.getParameter("method");
    //通过方法名获取到方法的对象
      //获取当前类的Class对象
        Class cla = this.getClass();
      //获取cla的方法(Method对象)
        //getDeclaredMethod需要两个参数,方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
      try {
        //获取方法对象
          Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class);
        //设置方法的访问权限
          method.setAccessible(true);     //该方法可以取消Java的权限控制检查,就可以调用类的私有属性和方法
        //调用方法
        //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数
          method.invoke(this, request , response);         //方法调用,传递调用对象及参数
      } catch (Exception e) {
        e.printStackTrace();
      }

 二、反射的应用

  1、新建的Servlet继承BaseServlet类,不需要重写doGet和doPost方法,直接写不同的处理方法,注意方法名要与methodName的值相匹配

  2、执行流程:

      页面提交表单到对应Servlet

      该Servlet由于继承了BaseServlet类,会调用父类的doGet或doPost方法,

      通过页面获取的参数,调用该Servlet对应名称的方法

原文地址:https://www.cnblogs.com/liubin1988/p/7902791.html