2019-05-31

servlet抽取

刚刚学习使用servlet写后台,往往只使用一个servlet来处理一个功能,但是随着项目规模加大,页面增多,众多的servlet让人很是心烦,这时候就需要向上抽取serlvet了

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取相对地址
        String servletPath = req.getRequestURI ();
        System.out.println (servletPath);
        //获取相对地址的末尾,用来确定要执行的方法
        String methodname = servletPath.substring (servletPath.lastIndexOf ("/") + 1);
        System.out.println (methodname);
        //利用反射机制来执行方法
        // 在继承中,如果this.成员,那么指向的是当前类的成员,因为成员没有复写的机制。但是如果this.方法,那么this指向的方法要从子类中找,如果没找到在逐层向父类中找
        try {
            Method method = this.getClass ().getMethod (methodname, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke (this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace ();
        } catch (IllegalAccessException e) {
            e.printStackTrace ();
        } catch (InvocationTargetException e) {
            e.printStackTrace ();
        }
    }
}

下面我们来分析上述代码用到的思路
1.使用request的getRequestURI方法,返回请求的部分路径
2.使用字符串的相关方法查分拆分路径,获得最后一部分
3.通过this.class获得子类的字节码文件(反射机制),然后调用method.invoke来执行对应名字的方法。

顺便附上反射机制中获取Class对象的方式:

    1. Class.forName("全类名"):将字节码文件加载进内存,返回Class对象
         多用于配置文件,将类名定义在配置文件中。读取文件,加载类
    2. 类名.class:通过类名的属性class获取
        多用于参数的传递
    3. 对象.getClass():getClass()方法在Object类中定义着。
        多用于对象的获取字节码的方式
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。