在web.xml配置自定义的servlet来访问加载所需资源
//加载配置文件
private void loadConfig(ServletConfig config) {
boolean b = false;
String configFile = config.getInitParameter("config").trim();
//判断参数是否包含classpath
if(configFile.contains("classpath")){
configFile = configFile.substring(configFile.indexOf("classpath")+10);
b = true;
}
//检测是否包含分隔符
String[] files = configFile.split(",");
for (int i = 0 , j = files.length; i < j; i++) {
String filestr = files[i];
//获取参数指定文件路径
int index = filestr.lastIndexOf("/");
String cpath = filestr.substring(0, index);
String fileName = filestr.substring(index+1);
String wpath = null;
if(b){
//通过类加载器加载资源路径
wpath = this.getClass().getClassLoader().getResource(cpath).getPath();
}else{
//
wpath = this.getServletContext().getRealPath(cpath);
}
//判断路径存不存在
File dir = new File(wpath);
if(!dir.exists()){
System.err.println((new StringBuilder("Warning directory:"))
.append(wpath).append("不存在!").toString());
}else{
File[] listfile = dir.listFiles();
listResource = new ArrayList
//检测是否包含通配符
if(fileName.contains("*")){
//获取文件通配符正则表达式
String regexp = fileName.replace("*", "[\\s\\S]*");
for (int t = 0; t < listfile.length; t++) {
File file = listfile[t];
if(file.isDirectory()){//若是目录则继续匹配下一个文件
continue;
}
if(file.getName().matches(regexp)){
listResource.add(file);
System.out.println("Load directext config:" + file.getAbsolutePath());
}
}
}else{
File file = new File(new StringBuilder(wpath).append("/").append(fileName).toString());
if(!file.exists()){
System.err.println((new StringBuilder("Warning file:"))
.append(file.getAbsolutePath()).append("不存在!").toString());
}
listResource.add(file);
System.out.println("Load directext config:" + new StringBuilder(file.getAbsolutePath()));
}
}
}
}