我正在使用spring MVC。在我的應用程序中,用戶應該能夠以多種語言(英語,日語,中文,波蘭語等)發佈評論/文本。這些帖子也會存儲在數據庫中。那麼如何在我的UI端和服務器端啓用多語言支持Spring MVC:多語言支持
我需要做什麼事情。我看到一些國際化的例子,但我的困惑是它使用屬性文件來存儲每個單詞的含義。這就是我如何存儲每一個單詞的問題。這是我需要的東西嗎?一個例子將足夠好
我正在使用spring MVC。在我的應用程序中,用戶應該能夠以多種語言(英語,日語,中文,波蘭語等)發佈評論/文本。這些帖子也會存儲在數據庫中。那麼如何在我的UI端和服務器端啓用多語言支持Spring MVC:多語言支持
我需要做什麼事情。我看到一些國際化的例子,但我的困惑是它使用屬性文件來存儲每個單詞的含義。這就是我如何存儲每一個單詞的問題。這是我需要的東西嗎?一個例子將足夠好
是的,你需要做的事情告訴你的例子。您不必存儲含義,但您必須爲要在UI中實現國際化的每個字符串都有一個屬性。
你需要認識到Spring I18N的例子只涉及不同語言的UI顯示。數據庫中的多語言將需要單獨的努力。
你需要更多的專業知識,比你從這裏或網上的例子中得到的更多。
網站大多具有語言鏈接(即EN英語,FR爲法語等)。因此,根據用戶選擇的語言鏈接,您可以找出不同的語言。
另一種方法是進行某種自動檢測,因此如果用戶輸入某些特定語言的常用單詞,則可以突出顯示自動選擇的語言,並且還可以讓用戶選擇重寫自動檢測並手動選擇語言。一個很好的例子就是谷歌的translate website。
此外,請確保從前端到後端的每個組件均設置爲UTF-8編碼。也就是說,您的Web /應用程序服務器(例如Tomcat),您的應用程序框架(例如Spring)和您的數據庫(包括IDE設置),並且包括jsp/html文件的所有文件都保存爲UTF-8編碼並聲明UTF-如在您的jsp/html文件中有... <%@ page language="java" session="false" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
和<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
)。
對於具有數據庫使用的Spring l18n擴展AbstractMessageSource。 Java的conifg:
@Bean
public MessageSource messageSource(){
DataBaseMessageSource source = new DatabaseMessageSource();
return source;
}
@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.ENGLISH); //setup default locale
return resolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang"); //will change current user locale when hit url with ?lang
registry.addInterceptor(interceptor);
}
和
public class DatabaseMessageBandle extends AbstractMessageSource {
@Autowired
private FooRepository fooRepo;
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
String message = getMessage(code, locale);
MessageFormat messageFormat = createMessageFormat(message, locale);
return messageFormat;
}
@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
return getMessage(code, locale);
}
private String getMessage(String code, Locale locale) {
String message = fooRepo.getMeesageByCodeAndLocale(code, locale); //better not do this
return message;
}
}
,如果你需要獲得當前區域控制器:
@RequestMapping
public String index(Locale locale) { //you will have it
//or use LocaleContextHolder.getLocale, and it will return current thread locale
return "index";
}
多語言支持不涉及翻譯用戶的內容,只是內容提供由應用程序。如果用戶使用波蘭語進行評論,則所有其他用戶都將看到波蘭語評論,無論他們選擇了哪種語言。 – Qwerky
所以如果已經設置了UTF-8編碼並且在數據庫中存儲任何語言的用戶類型。當我在沒有做任何額外工作的情況下將它顯示在網頁上時,我會得到同樣的結果嗎? – manish