在Ubuntu环境下为Java应用添加国际化支持,核心步骤如下:
创建资源文件
在src/main/resources目录下创建不同语言的.properties文件,如messages_en.properties(英文)、messages_zh_CN.properties(简体中文),文件中定义键值对(如welcome.message=欢迎使用我们的应用程序!)。
配置资源加载
MessageSource和LocaleResolver Bean,例如:<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
并配置拦截器处理语言切换:<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
ResourceBundle类手动加载资源文件,例如:Locale locale = new Locale("zh", "CN");
ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
String message = bundle.getString("welcome.message");
设置语言环境
?lang=zh_CN)、Session或Cookie传递用户语言偏好。LocaleChangeInterceptor自动解析URL参数。在代码中使用国际化文本
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="messages" />
<h1><fmt:message key="welcome.message" /></h1>
ResourceBundle获取文本。处理日期、数字等格式
使用DateFormat、NumberFormat类并指定Locale,例如:
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
String formattedDate = dateFormat.format(new Date());
测试验证
通过切换不同语言参数,验证界面文本、日期格式等是否正确显示。
说明:Ubuntu环境无需额外配置,核心依赖Java标准库和Spring框架(若使用)。资源文件需放置于类路径下,确保应用可访问。