欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(tomcat中级)应用Tomcat的WebappClassLoader加载指定目录的jar文件

程序员文章站 2022-07-15 14:35:57
...

要点

  1. 用WebappClassLoader::addRepository就可以实现。不用扩展WebappClassLoader类。
  2. 当ServletContextListener::contextInitialized时,调用addRepository。
  3. 在各个context-param中指定jar所在路径。

ServletContextListener

package cn.net.tianyu.classloader.servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.catalina.loader.WebappClassLoader;

public class ClassLoadListener implements ServletContextListener {

	private static final String CONTEXT_PARAM_NAME_EXTLIBPATH = "net.tianyu.servlet.extlibs";

	@Override
	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		addJar(context);
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {

	}

	synchronized private void addJar(ServletContext context) {

		String extlibs = context.getInitParameter(CONTEXT_PARAM_NAME_EXTLIBPATH);

		if (extlibs == null || extlibs.length() == 0)
			return;

		WebappClassLoader loader = (WebappClassLoader) getClass().getClassLoader();

		StringTokenizer st = new StringTokenizer(extlibs, ",");
		while (st.hasMoreTokens()) {
			String jarPath = st.nextToken();
			String jarRealPath = context.getRealPath(jarPath);

			File jarDir = new File(jarRealPath);
			if (!jarDir.isDirectory())
				continue;
			File[] jarFiles = jarDir.listFiles(new JarFileNameFilter());
			for (File jarFile : jarFiles) {
				try {
					loader.addRepository(jarFile.toURI().toURL().toString());
				} catch (MalformedURLException e) {
				}
			}
		}
	}

	class JarFileNameFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".jar");
		}
	}

}

 web.xml

<?xml version="1.0" encoding="Shift_JIS"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <context-param>
    <param-name>net.tianyu.servlet.extlibs</param-name>
    <param-value>/../../extlib,/../../otherlib</param-value>
  </context-param>

  <listener>
    <listener-class>cn.net.tianyu.classloader.servlet.ClassLoadListener</listener-class>
  </listener>

	<servlet>
		<servlet-name>sample</servlet-name>
		<servlet-class>cn.net.tianyu.classloader.servlet.SampleServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>sample</servlet-name>
		<url-pattern>/sample</url-pattern>
	</servlet-mapping>
</web-app>