如何解析URL路径,获取文件名,然后使用JSTL和Java scriptlet替换文件扩展名 [英] How do I parse through a URL path, get the filename, then replace the file extension using JSTL and Java scriptlet
问题描述
我需要从URL获取文件名"
I need to get "filename" from a URL
我在这里声明
<p:out var="path" value="${webObject.path}" scope="page"/>
<c:set var="string1" value="${path}" />
<p:out value="${string1}" />
这将在网页上返回"dir1/dir2/dir3/filename.xml"
this returns "dir1/dir2/dir3/filename.xml" on the webpage
我需要的是一个Java Scriptlet,它可以接收正在生成的URL(dir1/.../filename.xml),并获取"filename",其中没有目录,而最后没有.xml.
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.
推荐答案
不要使用 Scriptlets .在 JSTL函数中使用 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" -->
如果您确实需要为此编写Java代码,请考虑使用EL函数.例如
If you really need to write Java code for this, consider an EL function. E.g.
<c:set var="basename" value="${util:basename(path)}" />
与
public static String basename(String path) {
String[] pathparts = path.split("/");
String filename = pathparts[pathparts.length - 1];
return filename.split("\\.")[0];
}
如何注册EL函数,请查看 JSP/Servlet的隐藏功能.
How to register an EL function, look at the example somewhere near bottom of Hidden features of JSP/Servlet.
这篇关于如何解析URL路径,获取文件名,然后使用JSTL和Java scriptlet替换文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!