java web下载zip文件,JavaWeb项目加载resources(WEB-INF/classes/)目录下的jar/zip包到classpath...

需要两个步骤新建一个Listener,用于在容器初始化时扫描WEB-INF/classes/目录下的jar包。import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import java.io.File;

import java.io.FilenameFilter;

import java.lang.reflect.Method;

import java.net.URL;

import java.net.URLClassLoader;

public class LoadingJarListener implements ServletContextListener{

public void contextInitialized(ServletContextEvent sce) {

//加载resource下的jar

System.out.println("loading resources jar...");

String path = this.getClass().getResource("/").getPath();

System.out.println(path);

// jar的路径

File libPath = new File(path);

// 获取所有的.jar和.zip文件

File[] jarFiles = libPath.listFiles(new FilenameFilter() {

public boolean accept(File dir, String name) {

return name.endsWith(".jar") || name.endsWith(".zip");

}

});

if (jarFiles != null) {

// 从URLClassLoader类中获取类所在文件夹的方法

// 对于jar文件,可以理解为一个存放class文件的文件夹

Method method = null;

boolean accessible = false;

try {

method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);

accessible = method.isAccessible(); // 获取方法的访问权限

if (accessible == false) {

method.setAccessible(true); // 设置方法的访问权限

}

//加载jar到classpath

URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

for (File file : jarFiles) {

URL url = file.toURI().toURL();

try {

method.invoke(classLoader, url);

System.out.println(String.format("加载jar文件[name=%s]", file.getName()));

} catch (Exception e) {

System.err.println(String.format("加载jar文件[name=%s]失败", file.getName()));

}

}

} catch (Exception e) {

e.printStackTrace();

}finally {

if(method != null){

method.setAccessible(accessible);

}

}

}

}

public void contextDestroyed(ServletContextEvent sce) {

}

}

2.在web.xml中配置刚才写的listener。

LoadingJarListener

提醒:此方法是通过IO读取jar/zip文件,发布的war包必须解压后运行才管用。

最后编辑时间为: August 11th , 2017 at 02:11 pm

本文由 wjy 创作,采用 知识共享署名 4.0 国际许可协议进行许可

可自由转载、引用,但需署名作者且注明文章出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值