Java Thymeleaf上下文URL处理-如何向上下文相关URL添加语言代码(Spring+;Thymeleaf)
我已经编写了请求过滤器和区域设置解析器,用于从URL获取语言代码。(例如:DOMAIN/en/,DOMAIN/cs/) 但是,我不知道如何以编程方式更改Thymeleaf用于其上下文相关URL(@{/css/main.css})的上下文路径 例如,如果在地址为“DOMAIN/en/test/”的页面上,以下代码Java Thymeleaf上下文URL处理-如何向上下文相关URL添加语言代码(Spring+;Thymeleaf),java,spring,url,filter,thymeleaf,Java,Spring,Url,Filter,Thymeleaf,我已经编写了请求过滤器和区域设置解析器,用于从URL获取语言代码。(例如:DOMAIN/en/,DOMAIN/cs/) 但是,我不知道如何以编程方式更改Thymeleaf用于其上下文相关URL(@{/css/main.css})的上下文路径 例如,如果在地址为“DOMAIN/en/test/”的页面上,以下代码 <a th:href="@{/test2/}">TEST 2</a> 而不是 DOMAIN/en/test2/ 我认为在URL进入Thymeleaf模板之前创
<a th:href="@{/test2/}">TEST 2</a>
而不是
DOMAIN/en/test2/
我认为在URL进入Thymeleaf模板之前创建一些过滤器来编辑URL会很好,但我不知道如何创建
你有什么办法解决这个问题吗 一种解决方案是将URL放在消息资源文件中:
<a th:href="@{#{orders.details.localized_url}(id=${order.id})}">
我更喜欢第一个我找到了符合我期望的解决方案 我只是想在Thymeleaf模板的上下文路径(example.com/context\u path/CONTROLLER->example.com/context\u path/language\u code/CONTROLLER)之后插入语言代码,所以我仍然可以使用Thymeleaf的url表达式@{/CONTROLLER} 我有一个url过滤器,可以删除语言代码并将其添加到请求的属性中,因此我刚刚编辑了响应的encodeURL方法,它可以按照我的要求工作:
getServletContext().getRequestDispatcher(newUrl).forward(request, new HttpServletResponseWrapper(response) {
@Override
public String encodeURL(String url) {
String contextPath = getServletContext().getContextPath();
if (url.startsWith(contextPath))
url = new StringBuilder(url).insert(contextPath.length(), "/" + getLocale().getLanguage()).toString();
return super.encodeURL(url);
}
});
无论如何,谢谢你的回答!:) 我不会将语言添加到url中,您可以将其存储在用户会话中,并根据需要加载资源、css、i18,但不会因为用户更改语言而修改url我认为就SEO而言,建议为不同的语言使用不同的url。。。很多网站都使用它。没有办法吗?
@RequestMapping("/localized/**")
public String getTemplateView(HttpServletRequest request) {
String path = request.getRequestURI();
//path = /localized/en/mypage
return mypage_en.html;// or relative location in the configured folder
}
getServletContext().getRequestDispatcher(newUrl).forward(request, new HttpServletResponseWrapper(response) {
@Override
public String encodeURL(String url) {
String contextPath = getServletContext().getContextPath();
if (url.startsWith(contextPath))
url = new StringBuilder(url).insert(contextPath.length(), "/" + getLocale().getLanguage()).toString();
return super.encodeURL(url);
}
});