你能用JSTL c:if来测试网址模式吗?

Ton*_*y R 7 url jsp jstl el

我正在尝试使用当前URL运行的JSP条件.基本上我想做一些事情,如果URL结束/my-suffix,不包括查询字符串等.所以我需要测试中间的url的子字符串.

<c:if test="url not including query string+ ends with '/my-suffix'">
  do something...
</c:if>
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Bal*_*usC 15

检查JSTL函数taglib.其中一个可用的功能是fn:endsWith().这允许您例如:

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:if test="${not fn:endsWith(pageContext.request.requestURI, '/my-suffix')}">
    <p>URL does not end with /my-suffix.</p>
</c:if>
Run Code Online (Sandbox Code Playgroud)

(不包含查询字符串的${pageContext.request.requestURI}返回HttpServletRequest#getRequestURI())

或者,如果您已经使用了兼容Servlet 3.0的容器(如Tomcat 7,Glassfish 3等),那么您也可以直接使用参数调用方法,例如String#endsWith():

<c:if test="${not pageContext.request.requestURI.endsWith('/my-suffix')}">
    <p>URL does not end with /my-suffix.</p>
</c:if>
Run Code Online (Sandbox Code Playgroud)