1

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
brian
  • 11
  • 1
  • 2

1 Answers1

4

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555