Search code examples
javajspurljstlel

Composing URL in JSP


Lets say my current URL is: /app.jsp?filter=10&sort=name.

I have a pagination component in JSP which should contain links like:
/app.jsp?filter=10&sort=name&page=xxx.

How do I create valid URLs in JSP by adding new parameters to current URL? I dont want use Java code in JSP, nor end up with URLs like:
/app.jsp?filter=10&sort=name&?&page=xxx, or /app.jsp?&page=xxx, etc.


Solution

  • Ok, I found answer. First problem is that I have to preserve all current parameters in URL and change only page parameter. To do this I have to iterate over all current parameters and add those I don't want to change to URL. Then I added parameters I want to either change or add. So I ended up with solution like this:

    <c:url var="nextUrl" value="">
        <c:forEach items="${param}" var="entry">
            <c:if test="${entry.key != 'page'}">
                <c:param name="${entry.key}" value="${entry.value}" />
            </c:if>
        </c:forEach>
        <c:param name="page" value="${some calculation}" />
    </c:url>
    

    This will create nice and clean URL independent of page parameter in request. Bonus to this approach is that URL can be just anything.