1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class ServletTools {
private static Logger logger = Logger.getLogger(ServletTools.class);
private ServletTools() {
}
/**
* Search the absolutepath of a path with this algorithm : 1) if the path
* starts with '/', looking in the webapp's path root 2) if not found,
* looking in the classpath 3) if the path doesn't start with '/', returns
* path. If the path doesn't exist or there is an exception,
* <code>null</code> is returned
*
* @param servlet
* The servlet where we can find the path
* @param path
* The path to find
* @return The absolutepath of the path or <code>null</code> if the path
* doesn't exist
*/
public static String pathToAbsolutePath(HttpServlet servlet, String path) {
String absolutePath = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = servlet.getClass().getClassLoader();
}
try {
// Process each specified resource path
if (path.charAt(0) == '/') {
URL resource = null;
// Is the path in the webapp's path root?
resource = servlet.getServletContext().getResource(path);
if (resource == null) {
// Is the path in the classpath?
resource = loader.getResource(path);
}
absolutePath = urlToString(resource, path, servlet);
} else {
absolutePath = path;
}
} catch (MalformedURLException e) {
logger.error(ExceptionTools.toString(e));
absolutePath = null;
} catch (UnsupportedEncodingException e) {
logger.error(ExceptionTools.toString(e));
absolutePath = null;
}
return absolutePath;
}
private static String urlToString(URL url, String path, HttpServlet servlet)
throws UnsupportedEncodingException {
final String TYPE_FILE = "file:/";
final String TYPE_JNDI = "jndi:/";
String string = null;
if (url != null) {
String externalForm = url.toExternalForm();
if (externalForm.startsWith(TYPE_FILE)) {
string = externalForm.substring(TYPE_FILE.length());
string = URLDecoder.decode(string, "UTF-8");
}
if (externalForm.startsWith(TYPE_JNDI)) {
string = servlet.getServletContext().getRealPath(path);
}
}
return string;
}
} |
Partager