问题
I need to get "filename" from a URL
Here I am declaring
<p:out var="path" value="${webObject.path}" scope="page"/>
<c:set var="string1" value="${path}" />
<p:out value="${string1}" />
this returns "dir1/dir2/dir3/filename.xml" on the webpage
What I need is a Java Scriptlet that takes the URL being produced (dir1/.../filename.xml) and gets the 'filename' with no directories in front and no .xml at the end.
回答1:
Don't use Scriptlets. Use JSTL functions in EL.
<c:set var="pathparts" value="${fn:split(path, '/')}" /> <!-- String[] with values "dir1", "dir2", "dir3" and "filename.xml" -->
<c:set var="filename" value="${pathparts[fn:length(pathparts) - 1]}" /> <!-- Last item of String[]: "filename.xml" -->
<c:set var="basename" value="${fn:split(filename, '.')[0]}" /> <!-- Result: "filename" -->
If you really need to write Java code for this, consider an EL function. E.g.
<c:set var="basename" value="${util:basename(path)}" />
with
public static String basename(String path) {
String[] pathparts = path.split("/");
String filename = pathparts[pathparts.length - 1];
return filename.split("\\.")[0];
}
How to register an EL function, look at the example somewhere near bottom of Hidden features of JSP/Servlet.
来源:https://stackoverflow.com/questions/7017346/how-do-i-parse-through-a-url-path-get-the-filename-then-replace-the-file-exten