Can you use JSTL c:if to test against a url pattern?

14,323

Solution 1

Checkout the JSTL functions taglib. One of the available functions is fn:endsWith(). This allows you to for example do:

<%@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>

(the ${pageContext.request.requestURI} returns HttpServletRequest#getRequestURI() which does not include the query string)

Or, if you're already on a Servlet 3.0 compatible container which thus comes along with EL 2.2, such as Tomcat 7, Glassfish 3, etc, then you can also just invoke methods with arguments directly, such as String#endsWith():

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

Solution 2

To further add to BalusC's answer using the following would also work if you're looking to match a string anywhere in the url:

<c:if test="${fn:contains(pageContext.request.requestURI, 'my-string')}">
    <p>URL Contains my string</p>
</c:if>

Sidenote: Neither of our answers cover what the title is suggesting though (pattern matching) but that's not what the OP was looking to do in his post. That's actually little more involved but still doable (jstl doesn't have a regex match builtin apparently). If someone needs to do that create a separate post and link me to it and I'll try to help you out.

Share:
14,323
Tony R
Author by

Tony R

Updated on June 05, 2022

Comments

  • Tony R
    Tony R almost 2 years

    I'm trying to have a JSP conditional that operates on the current URL. Basically I want to do something if the URL ends in /my-suffix, NOT including the query string etc. So I need to test against a substring of the url that's right in the middle.

    <c:if test="url not including query string+ ends with '/my-suffix'">
      do something...
    </c:if>
    

    Is there a way to do this?

  • Tony R
    Tony R over 12 years
    What about eliminating the query string etc? Does request.requestURI not include that part?
  • BalusC
    BalusC over 12 years
    @Tony: no, it doesn't, as stated in my answer (click the javadoc link to see authoritative evidence "...up to query string..."). Is that a problem? Or didn't you tried it at all?
  • Tony R
    Tony R over 12 years
    Heh thanks BalusC, I am just distracted with other things. Whenever I get around to working on this again I'm sure your answer will get accepted (as if you needed the rep!) =P