Search code examples
javajspspring-mvcurljstl

Adding new parameter to current URL using JSTL


My application allows user to change language in any given moment and that cause me some trouble. For example if user specify page by URL: /category/8?page=3 and then would try to change the language by ?language=en it will erase previous parameters and take him to first page.

How can I get a current URL and add another parameter to it? I'd like to achieve something like this: /category/8?page=3&language=en when current ULR is /category/8?page=3 and user tried to change a language.

I tried using ${pageContext.request.requestURL} but that's not what I look for as it returns jsp page.


Solution

  • Here's a tag file I use. Save it as /WEB-INF/tags/replaceParam.tag:

    <%@ tag pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ attribute name="name" required="true" type="java.lang.String" %>
    <%@ attribute name="value" required="true" type="java.lang.String" %>
    
    <c:url value="">
    
        <%-- 
          replaces or adds a param to a URL
          if $name in query then replace its value with $value. 
          copies existing 
        --%>
    
        <c:forEach items="${paramValues}" var="p">
            <c:choose>
                <c:when test="${p.key == name}">
                    <c:param name="${name}" value="${value}"/>
                </c:when>
                <c:otherwise>
                    <c:forEach items="${p.value}" var="val">
                        <c:param name="${p.key}" value="${val}"/>
                    </c:forEach>
                </c:otherwise>
            </c:choose>
        </c:forEach>
    
        <%-- if $name not in query, then add --%>
        <c:if test="${empty param[name] }">
            <c:param name="${name}" value="${value}"/>
        </c:if>
    
    </c:url>
    

    Usage in another page (ex url is /category/9?page=3):

    <%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
    
    <my:replaceParam name='language' value='en' />
    

    output is /category/9?page=3&language=en