今天在修改项目一个JSP文件时,突然想到Tomat是怎么实现动态实时加载JSP编译后的class类的?

查了半天资料,看了很多文章,终于明白是怎么回事了:ClassLoader,当tomcat发现jsp改变后,将用新的ClassLoader去加载新的类

具体原理我将单独总结一下,这里简单实现了动态加载类

1.定义服务类

public class Servlet {

    public void service(){
System.out.println("运行服务方法");
} }

2.定义服务线程

public class ServiceThread extends Thread{

    public void run(){
try {
ClassLoader classLoader = this.getContextClassLoader();
Class clazz = classLoader.loadClass("Servlet");
Method service = clazz.getMethod("service", null);
service.invoke(clazz.newInstance(), null);
} catch (Exception e) {
e.printStackTrace();
}
}
}

3.自定义ClassLoader

public class MyClassLoader extends ClassLoader{

    @Override
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException{
try { // 我们要创建的Class对象
Class clasz = null; // 必需的步骤1:如果类已经在系统缓冲之中
// 我们不必再次装入它
clasz = findLoadedClass(name); if (clasz != null)
return clasz;
try {
// 读取经过加密的类文件
if(name.equals("Servlet")){
            //加载class文件字节
byte classData[] = Util.readFile(ProgramPathHelper.getProgramPath()+"/"+name + ".class");
if (classData != null) {
// ... 再把它转换成一个类
clasz = defineClass(name, classData, 0,
classData.length);
}
} } catch (Exception e) {
e.printStackTrace();
} // 必需的步骤2:如果上面没有成功
// 我们尝试用默认的ClassLoader装入它
if (clasz == null)
clasz = findSystemClass(name); // 必需的步骤3:如有必要,则装入相关的类
if (resolve && clasz != null)
resolveClass(clasz); // 把类返回给调用者
return clasz;
} catch (Exception ie) {
throw new ClassNotFoundException(ie.toString());
}
}
}

4.实现文件监听类

public class CCFileListener implements FileAlterationListener{

    public static HashMap<String,ClassLoader> claMap = new HashMap<String, ClassLoader>();

    ZJPFileMonitor monitor = null;
@Override
public void onStart(FileAlterationObserver observer) {
//System.out.println("onStart");
}
@Override
public void onDirectoryCreate(File directory) {
System.out.println("onDirectoryCreate:" + directory.getName());
} @Override
public void onDirectoryChange(File directory) {
System.out.println("onDirectoryChange:" + directory.getName());
} @Override
public void onDirectoryDelete(File directory) {
System.out.println("onDirectoryDelete:" + directory.getName());
} @Override
public void onFileCreate(File file) {
System.out.println("onFileCreate:" + file.getName());
dyncLoadClass(file.getName());
} @Override
public void onFileChange(File file) {
     //文件改变处理函数
System.out.println("onFileChange : " + file.getName()); dyncLoadClass(file.getName()); } private void dyncLoadClass(String className){
if(className.contains("Servlet")){
// ZJPFileMonitor.thread.setContextClassLoader(new MyClassLoader());
claMap.put(className, new MyClassLoader());
}
} @Override
public void onFileDelete(File file) {
System.out.println("onFileDelete :" + file.getName());
} @Override
public void onStop(FileAlterationObserver observer) {
//System.out.println("onStop");
} }
public class CCFileMonitor {

    FileAlterationMonitor monitor = null;
public CCFileMonitor(long interval) throws Exception {
monitor = new FileAlterationMonitor(interval);
} public void monitor(String path, FileAlterationListener listener) {
FileAlterationObserver observer = new FileAlterationObserver(new File(path));
monitor.addObserver(observer);
observer.addListener(listener);
}
public void stop() throws Exception{
monitor.stop();
}
public void start() throws Exception {
monitor.start();
}
public static void main(String[] args) throws Exception {
CCFileMonitor m = new CCFileMonitor(5000);
m.monitor(ProgramPathHelper.getProgramPath(),new CCFileListener());
m.start(); Servlet servlet = new Servlet();
servlet.service();
MyClassLoader defaultCl = new MyClassLoader();
while(true){ Thread.currentThread().sleep(3000); Thread t = new ServiceThread();
//设置新线程的类加载器
ClassLoader classLoader = CCFileListener.claMap.get("Servlet.class");
if(classLoader==null){
classLoader = defaultCl;
} t.setContextClassLoader(classLoader); t.start(); }
}
}
public static HashMap<String,ClassLoader> claMap = new HashMap<String, ClassLoader>();
在监听到文件改变后,依据类名重new一个类加载器,用于加载类。
 ClassLoader classLoader = CCFileListener.claMap.get("Servlet.class");
if(classLoader==null){
classLoader = defaultCl;
}
 首先获取类名对应的加载器,如果没有使用默认的加载器
 ClassLoader classLoader = this.getContextClassLoader();
Class clazz = classLoader.loadClass("Servlet");
Method service = clazz.getMethod("service", null);
service.invoke(clazz.newInstance(), null);
在线程内部使用刚才在外部设置的线程上下文加载器加载新的Servlet,并执行

学习Tomcat动态加载JSP的Class类的更多相关文章

  1. [WPF学习笔记]动态加载XAML

    好久没写Blogs了,现在在看[WPF编程宝典],决定开始重新写博客,和大家一起分享技术. 在编程时我们常希望界面是动态的,可以随时变换而不需要重新编译自己的代码. 以下是动态加载XAML的一个事例代 ...

  2. 从高德 SDK 学习 Android 动态加载资源

    前不久跑去折腾高德 SDK 中的 HUD 功能,相信用过该功能的用户都知道 HUD 界面上的导航转向图标是动态变化的.从高德官方导航 API 文档中 AMapNaviGuide 类的描述可知,导航转向 ...

  3. JS学习之动态加载script和style样式

    前提:我们可以把一个网页里面的内容理解为一个XML或者说网页本身也就是一个XML文档,XML文档都有很特殊的象征:"标签"也叫"节点".我们都知道一个基本的网页 ...

  4. Android学习——Fragment动态加载

    动态加载原理 利用FragmentManager来添加一套Fragment事务,最后通过commit提交该事务来执行对Fragment的相关操作. FragmentManager fragmentma ...

  5. tomcat解决加载JSP文件过大错误

    当遇到多个Jsp include一起的时候加载时遇到如下错误: Error:SEVERE: Servlet.service() for servlet jsp threw exception org. ...

  6. asp.net动态加载程序集创建指定类的实例及调用指定方法

    以下类中有三个方法: LoadAssembly:加载指定路径的程序集 GetInstance:根据Type动态获取实例,用泛型接到返回的类型 ExecuteMothod:执行实例中的指定方法 /// ...

  7. Vue – 基础学习(5):动态加载和注册组件

    // var myComponent =() => import(`./../../components/custom_panel/${t_url}.vue`);// //var myCompo ...

  8. 启动Tomcat自动加载(运行)类

    其实这是紧跟着我上次写的java计时器Timer的,因为Timer的测试类写好后,不可能要通过什么东西去触发,对已经存在的时间点进行监控 所以,在启动项目是自动运行此类 方法如下: 一.在web.xm ...

  9. 动态加载dll,并创建类对象放入到list中。

    private List<IVisualControlsPlug> visualPlugs = new List<IVisualControlsPlug>(); public ...

随机推荐

  1. (4.5.4)Android測试TestCase单元(Unit test)測试和instrumentationCase单元測试

    Android单元和instrumentation单元測试 Developing Android unit and instrumentation tests Android的单元測试是基于JUnit ...

  2. ASP.NET机制详细的管道事件流程(转)

    ASP.NET机制详细的管道事件流程 第一:浏览器向服务器发送请求. 1)浏览器向iis服务器发送请求网址的域名,根据http协议封装成请求报文,通过dns解析请求的ip地址,接着通过socket与i ...

  3. CPI

    CPI (Consumer Price Index 物价指数) 是政府用来衡量通货膨胀的其中一个数据.通俗的讲,CPI就是市场上的货物价格增长百分比.一般市场经济国家认为CPI在2-3%属于可接受范围 ...

  4. Spark源代码分析之六:Task调度(二)

    话说在<Spark源代码分析之五:Task调度(一)>一文中,我们对Task调度分析到了DriverEndpoint的makeOffers()方法.这种方法针对接收到的ReviveOffe ...

  5. 【BZOJ4052】[Cerc2013]Magical GCD 乱搞

    [BZOJ4052][Cerc2013]Magical GCD Description 给出一个长度在 100 000 以内的正整数序列,大小不超过 10^12.  求一个连续子序列,使得在所有的连续 ...

  6. Open-sourcing LogDevice, a distributed data store for sequential data

    https://logdevice.io/blog/2018/09/12/open-sourcing-announcement.html September 12, 2018   We are exc ...

  7. svn服务器 vim 修改 authz passwd 添加用户

    进入svn服务器 vim 修改 authz passwd 添加用户 SVN服务器之------2,配置PhpStorm连接SVN服务器(其他IDE大同小异) - 学到老死 - 博客园 https:// ...

  8. 【题解】 AT2134 Zigzag MST

    [题解]AT2134 Zigzag MST 一道MST好题 \(Anson\)有云: 要么是减少边的数量. 要么是改变连接边的方式. 那么如何减少边的数量呢?很简单,把所有不可能对答案产生贡献的边去掉 ...

  9. nvl()与regexp_replace()

    NVL(字段,0):将空值转化为0 regexp_replace(字段, ‘[1-9]‘ ,'') is not null; 将数字转化为0

  10. Java for LeetCode 098 Validate Binary Search Tree

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...