zoukankan      html  css  js  c++  java
  • 反射实现定位Servlet中的方法

    public class BaseServlet extends HttpServlet{
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //设置编码表
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            // 接收参数:
            String methodName = req.getParameter("method");
            //如果method传递的参数为null或者为空字符串,作出提示
            if(methodName == null || "".equals(methodName)){
                resp.getWriter().println("method参数为null!!!");
                return;
            }
            // 获得子类的Class对象:
            /**
             * this.class代表加载继承了这个BaseServlet的class对象
             * */
            Class clazz = this.getClass();
            // 获得子类中的方法了:
            try {
                Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
                // 使方法执行,并获取子类return的字符串
                String path = (String)method.invoke(this, req,resp);
                //转发
                if(path != null){
                    req.getRequestDispatcher(path).forward(req, resp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
  • 相关阅读:
    数据公钥加密和认证中的私钥公钥
    hibernate数据的三种状态
    寄存器和立即数和内存单元
    三条总线作用
    liunx安装redis和gcc
    Python遍历列表
    String.split()分割字符串方法
    Jmeter教程 录制脚本
    Jemeter压力测试
    Jmeter性能测试
  • 原文地址:https://www.cnblogs.com/lychee-wang/p/9909673.html
Copyright © 2011-2022 走看看