1

I want to capture the base path of 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?

qodeninja
  • 10,946
  • 30
  • 98
  • 152

1 Answers1

1

This functionality doesn't exist in JSTL. Closest is the fn:replace(), but it doesn't support regular expressions. The other functions provides the possibility to get rid of the leading part until with the domain (using fn:substringAfter() a several times on // and /), but there's nothing which makes it easy to get rid of the trailing part. Maybe with a whole bunch of fn:substringAfter and c:set in a loop, but it would make the code clumsy and not really reuseable.

Well, in regex you could use ^[^/]+/+[^/]+|[^/]+$ for this:

url = url.replaceAll("^[^/]+/+[^/]+|[^/]+$", "");

You could create a custom EL function which 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 a /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 you can import as:

<%@taglib uri="http://example.com/functions" prefix="f" %>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Won't it be nicer to use http://java.sun.com/javase/6/docs/api/java/net/URL.html and getProtocol(), getHost(), etc ? – Bozho Apr 10 '10 at 05:25
  • @Bozho: that was also the first where I looked, but it doesn't have methods to return exactly the desired string. The `getPath()` comes close, but you would still need to substring/replace the last part off. Also, constructing an `URL` is a bit more expensive. So I thought, let's give an generic example with `String#replaceAll()`, which may have more uses than this. – BalusC Apr 10 '10 at 20:18