How can I parse a url using JSP / JSTL?
I want to grab the base path for a given url
http://mydomain.com/mypath/coolpath/favoritepath/file.htm
so basically I just want this:
/ mypath / coolpath / favoritepath /
Any ideas how to do this without using straight Java?
a source to share
This feature does not exist in JSTL. The closest is fn:replace()
, but it doesn't support regular expressions. Other functions provide the ability to get rid of the leading part before the domain (using fn:substringAfter()
a multiple times on //
and /
), but there is nothing that makes it easier to get rid of the back part. Maybe with a whole series fn:substringAfter
and c:set
in a loop, but this will make the code clunky and won't really be reused.
Well, in regex, you can use ^[^/]+/+[^/]+|[^/]+$
for this:
url = url.replaceAll("^[^/]+/+[^/]+|[^/]+$", "");
You can create a custom EL function that does exactly this:
${f:replaceAll(url, '^[^/]+/+[^/]+|[^/]+$', '')}
To achieve this, first create a class like this:
package com.example;
public final class Functions {
private Functions() {}
public static String replaceAll(String string, String pattern, String replacement) {
return string.replaceAll(pattern, replacement);
}
}
and create /WEB-INF/functions.tld
like this:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<display-name>Custom Functions</display-name>
<tlib-version>1.0</tlib-version>
<uri>http://example.com/functions</uri>
<function>
<name>matches</name>
<function-class>com.example.Functions</function-class>
<function-signature>java.lang.String replaceAll(java.lang.String, java.lang.String, java.lang.String)</function-signature>
</function>
</taglib>
which can be imported as:
<%@taglib uri="http://example.com/functions" prefix="f" %>
a source to share