3

I'm using Spring MVC LocaleChangeInterceptor to handle change of locale. I need 2 simple links to switch the current page between English and French while keeping any existing parameter of the current URL.

The solution I've came up with looks rather ugly. A c:url tag with an empty value to link to the current page and a loop to append any existing parameter except for the language parameter that I don't want to see twice. So the code is as follow.

<c:url value="" var="englishURL">
    <c:forEach items="${param}" var="currentParam">
        <c:if test="${currentParam.key != 'siteLanguage'}">
            <c:param name="${currentParam.key}" value="${currentParam.value}"/>
        </c:if>
    </c:forEach>
    <c:param name="siteLanguage" value="en"/>
</c:url>
<c:url value="" var="frenchURL">
    <c:forEach items="${param}" var="currentParam">
        <c:if test="${currentParam.key != 'siteLanguage'}">
            <c:param name="${currentParam.key}" value="${currentParam.value}"/>
        </c:if>
    </c:forEach>
    <c:param name="siteLanguage" value="fr"/>
</c:url>
<a href="${englishURL}">English</a> / <a href="${frenchURL}">Français</a>

Does someone have a less ugly way to create these links? I know I can create a custom tag to avoid the duplication but I feel that's a very small improvement since I need to declare the tag and all.

4

2 回答 2

2

不是真的不那么难看,但至少代码重复更少

<c:forEach var="tuple" items="${fn:split('en,English|fr,Français|nl,Nederlands', '|')}" varStatus="status">
  <c:set var="locale" value="${fn:split(tuple, ',')[0]}"/>
  <c:set var="name" value="${fn:split(tuple, ',')[1]}"/>
  <c:url value="" var="url">
    <c:forEach items="${param}" var="currentParam">
      <c:if test="${currentParam.key != 'changeLocale'}">
        <c:param name="${currentParam.key}" value="${currentParam.value}"/>
      </c:if>
    </c:forEach>
    <c:param name="changeLocale" value="${locale}"/>
  </c:url>
  <a href="${url}">${name}</a>
  <c:if test="${not status.last}"> / </c:if>
</c:forEach>
于 2012-07-18T08:40:11.607 回答
0

从您的问题来看,您似乎每次都在您的网址中附加了 siteLanguage 参数。这是对的吗?为什么你需要这样做?您可以将此语言更改保存在会话或 cookie 中,然后每次不需要指定 siteLanguage 参数。选择语言后,语言参数将存储在会话或 cookie 中。Spring 将自己管理其余的事情。

只需指定 SessionLocaleResolver 或 CookieLocaleResolver 以及您的 LocaleChangeInterceptor。它会为你做到这一点。

希望这对您有所帮助。干杯。

于 2012-06-20T06:11:38.767 回答