1 package jfun.yan.web; 2 3 import java.io.InputStream ; 4 import java.net.MalformedURLException ; 5 import java.net.URL ; 6 7 import javax.servlet.ServletContext ; 8 9 import jfun.yan.util.resource.ResourceLoader; 10 11 18 public class ServletContextResourceLoader implements ResourceLoader { 19 private final ServletContext ctxt; 20 private final ResourceLoader loader; 21 private static final String WEB_RESOURCE_PREFIX = "/"; 22 public ServletContextResourceLoader(ServletContext ctxt, 23 ResourceLoader loader) { 24 this.loader = loader; 25 this.ctxt = ctxt; 26 } 27 28 public URL getResource(String path) { 29 if(isWebResource(path)){ 30 try{ 31 return ctxt.getResource(path); 32 } 33 catch(MalformedURLException e){ 34 return null; 35 } 36 } 37 else{ 38 return loader.getResource(path); 39 } 40 } 41 42 public InputStream getResourceAsStream(String path) { 43 if(isWebResource(path)){ 44 return ctxt.getResourceAsStream(path); 45 } 46 else{ 47 return loader.getResourceAsStream(path); 48 } 49 } 50 private static boolean isWebResource(String path){ 51 return path!=null && path.trim().startsWith(WEB_RESOURCE_PREFIX); 52 } 53 56 public ServletContext getServletContext(){ 57 return ctxt; 58 } 59 62 public ResourceLoader getResourceLoader(){ 63 return loader; 64 } 65 66 public boolean equals(Object obj) { 67 if(obj instanceof ServletContextResourceLoader){ 68 final ServletContextResourceLoader other = (ServletContextResourceLoader)obj; 69 return ctxt.equals(other.ctxt) && loader.equals(other.loader); 70 } 71 else return false; 72 } 73 74 public int hashCode() { 75 return ctxt.hashCode()*31+loader.hashCode(); 76 } 77 78 public String toString() { 79 return getClass().getName(); 80 } 81 82 } 83 | Popular Tags |