java - 如何在 I18n 中使用 Spring?

标签 java spring spring-mvc internationalization thymeleaf

我在 github 上有我的项目:https://github.com/QuentinVaut/JavaquariumEE

我听过很多教程,他们说了不同的话,我尝试实现教程中找到的解决方案,但没有错,我明白为什么。

你能告诉我我的项目有什么问题并解释一下吗?

许多教程和 Github 示例之一:

http://memorynotfound.com/spring-mvc-internationalization-i18n-example/

最佳答案

我粗略地浏览了那个教程。以下是我的做法:

首先配置它:

在返回MessageSource的配置类中创建一个Bean 执行。

@Bean
public MessageSource messageSource() //The bean must be named messageSource.
{
ReloadableResourceBundleMessageSource messageSource =
new ReloadableResourceBundleMessageSource();
messageSource.setCacheSeconds(-1); //cache time in seconds was set to -1. This disables reloading and makes the message source cache messages forever (until the JVM restarts).
messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
messageSource.setBasenames(
"/WEB-INF/i18n/messages", "/WEB-INF/i18n/errors"); //the message source is configured with the basenames /WEB-INF/i18n/messages and /WEB-INF/i18n/errors. This means that the message source will look for filenames like /WEB-INF/i18n/messages_en_US.properties, /WEB-INF/i18n/errors_fr_FR.properties
return messageSource;
}

现在创建一个返回 LocaleResolver 的 bean:

@Bean
public LocaleResolver localeResolver() //The bean must be named localeResolver.
{
return new SessionLocaleResolver();
}

这使得 LocaleResolver 可用于 DispatcherServlet 执行的任何代码。这意味着其他非 View JSP 无法访问 LocaleResolver。为了解决这个问题,您可以创建一个过滤器并像这样设置它:

private ServletContext servletContext;
private LocaleResolver = new SessionLocaleResolver();    
@Inject MessageSource messageSource;
...

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
request.setAttribute(
DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver
);
JstlUtils.exposeLocalizationContext(
(HttpServletRequest)request, this.messageSource
); 

现在您需要配置处理程序拦截器:

您在配置类中覆盖 WebMvcConfigurerAdapter 的 addInterceptors 方法以设置 LocaleChangeInterceptor(或任何其他拦截器):

@Override
public void addInterceptors(InterceptorRegistry registry)
{
super.addInterceptors(registry);
registry.addInterceptor(new LocaleChangeInterceptor());
}

现在您可以简单地在您的 Controller 上使用@Injected LocaleResolver。您只需在解析器上调用 setLocale 即可更新当前语言环境。

编辑:更具体的示例:

假设您有一个简单的 Controller :

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Map<String, Object> model)
{
model.put("date", new Date());
model.put("alerts", 12);
model.put("numCritical", 0);
model.put("numImportant", 11);
model.put("numTrivial", 1);
return "home/index";
}

然后假设您在/WEB-INF/i18n/下有 messages_en_US.properties 文件。此属性文件包含针对美国英语本地化的消息。

title.alerts=Server Alerts Page

alerts.current.date=Current Date and Time:

number.alerts=There {0,choice,0#are no alerts|1#is one alert|1

alert.details={0,choice,0#No alerts are|1#One alert is|1<{0,number,integer} > \ alerts are} critical. {1,choice,0#No alerts are|1#One alert is|1<{1,number,\ integer} alerts are} important. {2,choice,0#No alerts are|1#One alert \ is|1<{2,number,integer} alerts are} trivial.

然后,假设您在/WEB-INF/i18n/下有 messages_es_MX.properties 文件,并且该文件包含本地化的消息 墨西哥西类牙语。

title.alerts=Server Alertas Página

alerts.current.date=Fecha y hora actual: number.alerts={0,choice,0#No hay alertas|1#Hay una alerta|1

alert.details={0,choice,0#No hay alertas son críticos|1#Una alerta es \ crítica|1<{0,number,integer} alertas son críticos}. \ {1,choice,0#No hay alertas son importantes|1#Una alerta es importante\ |1<{1,number,integer} alertas son importantes}. \ {2,choice,0#No hay alertas son triviales|1#Una alerta es trivial\ |1<{2,number,integer} alertas son triviales}.

现在,您需要使用 <spring:message>在您的 JSP 中标记以在英语和西类牙语之间进行翻译。这是您的 jsp 页面的样子:

<spring:htmlEscape defaultHtmlEscape="true" />
<%--@elvariable id="date" type="java.util.Date"--%>
<%--@elvariable id="alerts" type="int"--%>
<%--@elvariable id="numCritical" type="int"--%>
<%--@elvariable id="numImportant" type="int"--%>
<%--@elvariable id="numTrivial" type="int"--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html>
<html>
<head>
<title><spring:message code="title.alerts" /></title>
</head>
<body>
<h2><spring:message code="title.alerts" /></h2>
<i><fmt:message key="alerts.current.date">
<fmt:param value="${date}" />
</fmt:message></i><br /><br />
<fmt:message key="number.alerts">
<fmt:param value="${alerts}" />
</fmt:message><c:if test="${alerts > 0}">
&nbsp;<spring:message code="alert.details">
<spring:argument value="${numCritical}" />
<spring:argument value="${numImportant}" />
<spring:argument value="${numTrivial}" />
</spring:message>
</c:if>
</body>
</html>

关于java - 如何在 I18n 中使用 Spring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42340827/

相关文章:

java - 如何用Python、C或Java读取大数据文件的一部分?

java - 无法提交 JPA 事务 - RollbackException : Transaction marked as rollbackOnly

spring boot @Cachable 返回填充了空值的父类(super class)的所有字段

java - Spring Boot Web 应用程序刷新后的白标错误页面

java - Spring WebClient 从 Json 请求中过滤 Null

java - 对字符串数组进行排序

java - spring boot 并行传出请求的最佳实践是什么?

java - Spring Boot Data JPA 查询不适用于 LocalDateTime.MAX

java - 将自定义参数添加到 spring mvc Controller

java - 使用 Table 标签为 gmail 和 yahoo 设计模板?