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();
            }
        }
    }
    
    
  • 相关阅读:
    什么是高可用?
    URL中两种方式传参
    Flask基本环境配置
    爬虫urlib库的一些用法
    HTML第一部分
    python中递归题
    python中重要的内置函数
    关于生成器中的send,应用移动平均值,以及yield from
    python中装饰器进阶
    一些作业
  • 原文地址:https://www.cnblogs.com/lychee-wang/p/9909673.html
Copyright © 2011-2022 走看看