How can I parse a URL using JSP/JSTL?

2019-07-28 10:52发布

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?

标签: jsp parsing jstl
1条回答
聊天终结者
2楼-- · 2019-07-28 11:31

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" %>
查看更多
登录 后发表回答