zoukankan      html  css  js  c++  java
  • 利用反射重构 Servlet

    BaseServlet

    package com.cn;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class BaseServlet extends HttpServlet {
    
        @Override
        public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            //根据请求的uri获取对应的请求方法 然后在执行对应的方法即可
            String requestURI = request.getRequestURI();
            int i = requestURI.lastIndexOf("/")+1;
            String method = requestURI.substring(i);   //@WebServlet("/userServlet/*")  这样就从uri中获取到了需要执行的方法
    
            // this 就是 com.cn.UserServlet@78d81ec1   //public class UserServlet extends BaseServlet {}
            //System.out.println(this);
            Class clazz = this.getClass();
            //获取字节码中所有的方法
            try {
                Method m = clazz.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
                m.invoke(this,request,response);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }
    }

    Servlet

    @WebServlet("/userServlet/*")
    public class UserServlet extends BaseServlet {
    
        public void hello(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("我是hello的方法");
        }
    
    
    }

    //启动测试 调用Hello方法

    http://localhost:8080/Re_Servlet/userServlet/hello
    坚持
  • 相关阅读:
    Zigbee学习路线
    Zigbee简介
    验证lagrange 定理
    为什么(12)式,km不能直接相乘?而要让域k先乘一个代数A里面的单位元,再作用在群M上呢?
    strong weak distribution
    sufficient statistics
    tensorflow TypeError: Can not convert a float32 into a Tensor or Operation
    tensorflow 训练的时候loss=nan
    tensorflow run()和 eval()
    python array基本操作一
  • 原文地址:https://www.cnblogs.com/gaoSJ/p/12978958.html
Copyright © 2011-2022 走看看