How do I parse through a URL path, get the filename, then replace the file extension using JSTL and Java scriptlet

…衆ロ難τιáo~ 提交于 2019-12-24 17:21:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!