Parse request URL in JSTL

JorgeO picture JorgeO · Mar 6, 2010 · Viewed 9.6k times · Source

I want to display a specific message based on the URL request on a JSP.

the request URL can be:

/app/cars/{id}

OR

/app/people/{id}

On my messages.properties I've got:

events.action.cars=My car {0} event
events.action.people=My person {1} event

Finally, on my JSP page I want to have the following code:

<spring:message code="events.${element.cause}.${?????}"
                arguments="${element.param['0']},${element.param['1']}"/>

I need help figuring out which expression I could use to parse the request URL and obtain the word before the ID.

Answer

BalusC picture BalusC · Mar 7, 2010

You can access the request URI in JSTL (actually: EL) as follows:

${pageContext.request.requestURI}

(which thus returns HttpServletRequest#getRequestURI())

Then, to determine it, you'll have to play a bit round with JSTL functions taglib. It offers several string manipulation methods like split(), indexOf(), substringAfter(), etc. No, no one supports regex. Just parse it.

Kickoff example:

<c:set var="pathinfo" value="${fn:split(pageContext.request.requestURI, '/')}" />
<c:set var="id" value="${pathinfo[pathinfo.length - 1]}" />

And use it as ${id}.