获取具有所有参数的完整当前URL百里香 [英] Get full current url thymeleaf with all parameters
问题描述
我在春季mvc中使用百里香叶.我想添加一个语言参数来更改语言环境.我是这样做的:
Im using thymeleaf with spring mvc. I want add a language param to change locale. I did it this way:
<a th:href="@{${currentUrl}(lang='es_ES')}" th:if="__${#locale}__ != 'es_ES'" >Sp</a>
<a th:href="@{${currentUrl}(lang='en_US')}" th:if="__${#locale}__ != 'en_US'" >Eng</a>
但是在某些视图中,URL中有参数.如何添加参数? 当我遇到特定参数时,我知道如何添加:
But in some views I have params in the URL. How I can add the parameters? I know how to add when I meet the specific parameter:
<a th:href="@{${currentUrl}(fooParam = ${fooValue}, lang='es_ES')}" th:if="__${#locale}__ != 'es_ES'" >Sp</a>
但是我不知道所有视图中所有参数的数量和名称.如何获取当前网址的所有参数?
But I know neither the number and name of all parameters in all views. How I can get all the parameters of the current url?
推荐答案
您可以尝试创建用于构建URL的params部分的实用程序服务.该实用程序方法将从列表中获取输入,并通过StringBuffer构建一个String.结果将是您手动编写param时编写的String.现在,您可以使用thymeleaf中内置的Pre-Parser语法来调用该实用程序并构建您的最终URL. 这里是示例:
You can try to create an utility service for building the params part of your URL. The utility method will get input from a List and build a String through StringBuffer. The result will be a String written as when you write param manually. Now you can use the Pre-Parser syntax built in thymeleaf to call the utility and build your final url. Here the example:
公用服务
@Service("thymeleafUtilsService")
public class ThymeleafUtilsService
{
public String buildMultiParamPartUrl(List<String> paramNames)
{
StringBuffer sb = new StringBuffer(0);
for ( String paramName : paramNames )
{
if ( sb.length() >= 0 )
{
sb.append(",");
}
sb.append(paramName).append("=${").append(paramName).append("}");
}
return sb.toString();
}
}
用于测试的控制器
@Controller("multiParamLinkController")
@RequestMapping(value = "/multiParamLink")
public class MultiParamLinkController
{
@RequestMapping(value =
{ "/",
"" }, method = RequestMethod.GET)
public String testMultiParamsGenerator(Model model)
{
List<String> paramNames = new ArrayList<>();
paramNames.add("fooValue");
paramNames.add("barValue");
paramNames.add("lang");
model.addAttribute("fooValue", "foo");
model.addAttribute("barValue", "bar");
model.addAttribute("lang", "US_us");
model.addAttribute("paramNames", paramNames);
return "multiParamLink/multiParamLink.html";
}
}
用于测试的HtmlTemplate:
HtmlTemplate for Test:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<a th:href="@{${currentUrl}(__${@thymeleafUtilsService.buildMultiParamPartUrl(paramNames)}__)}">myLink</a>
<h1>Result</h1>
<pre th:inline="text">[[@{${currentUrl}(__${@thymeleafUtilsService.buildMultiParamPartUrl(paramNames)}__)}]]</pre>
</body>
</html>
这是您从示例中得到的:
this is what you get with the example:
您现在可以自定义此示例以适合您的代码,例如解析Map而不是List或String ...
You can now customize this example to suit your code, like parsing a Map instead of List or String...
这篇关于获取具有所有参数的完整当前URL百里香的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!