使用JSTL将新参数添加到当前URL [英] Adding new parameter to current URL using JSTL
问题描述
我的应用程序允许用户在任何给定时刻更改语言,这给我带来了一些麻烦.例如,如果用户通过URL指定页面:/category/8?page=3
,然后尝试通过?language=en
更改语言,它将删除先前的参数并将其带到第一页.
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.
如何获取当前URL并向其添加另一个参数?我想实现以下目标:/category/8?page=3&language=en
,当当前的ULR为/category/8?page=3
,并且用户尝试更改语言时.
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.
我尝试使用${pageContext.request.requestURL}
,但这不是我想要的,因为它返回了jsp页面.
I tried using ${pageContext.request.requestURL}
but that's not what I look for as it returns jsp page.
推荐答案
这是我使用的标记文件.将其另存为/WEB-INF/tags/replaceParam.tag
:
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>
在其他页面中使用(例如url为/category/9?page=3
):
Usage in another page (ex url is /category/9?page=3
):
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<my:replaceParam name='language' value='en' />
输出为/category/8?page=3&language=en
这篇关于使用JSTL将新参数添加到当前URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!