如何使用JSP/JSTL解析URL? [英] How can I parse a URL using JSP/JSTL?

查看:81
本文介绍了如何使用JSP/JSTL解析URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获给定网址的基本路径

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/

/mypath/coolpath/favoritepath/

有没有在不使用直接Java的情况下如何做到这一点的想法?

Any ideas how to do this without using straight Java?

推荐答案

此功能在JSTL中不存在.最接近的是fn:replace(),但它不支持正则表达式.其他功能提供了直到域为止都可以除去前导部分(在///上多次使用fn:substringAfter()),但是没有什么可以轻易除去尾随部分.也许有很多fn:substringAfterc:set循环在一起,但这会使代码笨拙并且不能真正重用.

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("^[^/]+/+[^/]+|[^/]+$", "");

您可以创建一个自定义的EL函数来完成此任务:

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);
     }
}

并创建如下的/WEB-INF/functions.tld:

<?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>

您可以将其导入为:

<%@taglib uri="http://example.com/functions" prefix="f" %>

这篇关于如何使用JSP/JSTL解析URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆