1 16 17 package org.springframework.web.context.support; 18 19 import java.io.File ; 20 import java.io.FileNotFoundException ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.net.URL ; 24 25 import javax.servlet.ServletContext ; 26 27 import org.springframework.core.io.AbstractResource; 28 import org.springframework.core.io.Resource; 29 import org.springframework.util.Assert; 30 import org.springframework.util.StringUtils; 31 import org.springframework.web.util.WebUtils; 32 33 47 public class ServletContextResource extends AbstractResource { 48 49 private final ServletContext servletContext; 50 51 private final String path; 52 53 54 63 public ServletContextResource(ServletContext servletContext, String path) { 64 Assert.notNull(servletContext, "Cannot resolve ServletContextResource without ServletContext"); 66 this.servletContext = servletContext; 67 68 Assert.notNull(path, "path is required"); 70 if (!path.startsWith("/")) { 71 path = "/" + path; 72 } 73 this.path = StringUtils.cleanPath(path); 74 } 75 76 79 public final ServletContext getServletContext() { 80 return servletContext; 81 } 82 83 86 public final String getPath() { 87 return path; 88 } 89 90 91 96 public InputStream getInputStream() throws IOException { 97 InputStream is = this.servletContext.getResourceAsStream(this.path); 98 if (is == null) { 99 throw new FileNotFoundException ("Could not open " + getDescription()); 100 } 101 return is; 102 } 103 104 109 public URL getURL() throws IOException { 110 URL url = this.servletContext.getResource(this.path); 111 if (url == null) { 112 throw new FileNotFoundException ( 113 getDescription() + " cannot be resolved to URL because it does not exist"); 114 } 115 return url; 116 } 117 118 123 public File getFile() throws IOException { 124 String realPath = WebUtils.getRealPath(this.servletContext, this.path); 125 return new File (realPath); 126 } 127 128 133 public Resource createRelative(String relativePath) throws IOException { 134 String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); 135 return new ServletContextResource(this.servletContext, pathToUse); 136 } 137 138 143 public String getFilename() { 144 return StringUtils.getFilename(this.path); 145 } 146 147 151 public String getDescription() { 152 return "ServletContext resource [" + this.path + "]"; 153 } 154 155 156 159 public boolean equals(Object obj) { 160 if (obj == this) { 161 return true; 162 } 163 if (obj instanceof ServletContextResource) { 164 ServletContextResource otherRes = (ServletContextResource) obj; 165 return (this.servletContext.equals(otherRes.servletContext) && this.path.equals(otherRes.path)); 166 } 167 return false; 168 } 169 170 174 public int hashCode() { 175 return this.path.hashCode(); 176 } 177 178 } 179 | Popular Tags |