开发者

How can I parse a URL using JSP/JSTL?

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?


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" %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜