Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

jsp

jstl

el

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?

like image 658
Tony R Avatar asked Dec 05 '11 04:12

Tony R


1 Answers

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>
like image 156
BalusC Avatar answered Oct 17 '22 04:10

BalusC