在Ubuntu上實現JSP的國際化(i18n)主要涉及以下幾個步驟:
確保你的Ubuntu系統上已經安裝了Java和Tomcat。如果沒有,可以使用以下命令進行安裝:
sudo apt update
sudo apt install openjdk-11-jdk
sudo apt install tomcat9
確保Tomcat已經正確配置并且正在運行。你可以通過訪問http://localhost:8080來驗證Tomcat是否正常運行。
在項目的src/main/resources目錄下創建不同語言的資源文件。例如:
messages_en.properties (英文)messages_zh.properties (中文)示例內容:
messages_en.properties
welcome.message=Welcome to our application!
messages_zh.properties
welcome.message=歡迎使用我們的應用程序!
在JSP頁面中使用<fmt:message>標簽來引用資源文件中的鍵值對。首先,確保在JSP頁面頂部引入JSTL標簽庫:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
然后在JSP頁面中使用<fmt:message>標簽:
<fmt:setLocale value="${pageContext.request.locale}" />
<fmt:setBundle basename="messages" />
<h1><fmt:message key="welcome.message" /></h1>
為了根據用戶的語言偏好自動選擇正確的資源文件,可以使用Spring的LocaleResolver和LocaleChangeInterceptor。首先,添加Spring依賴:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
然后,在Spring配置文件中配置LocaleResolver和LocaleChangeInterceptor:
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
確保Tomcat能夠正確處理UTF-8編碼。編輯/etc/tomcat9/server.xml文件,在<Connector>標簽中添加URIEncoding="UTF-8"屬性:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
最后,重啟Tomcat以應用所有更改:
sudo systemctl restart tomcat9
現在,你可以通過在URL中添加lang參數來測試國際化功能。例如:
http://localhost:8080/your-app?lang=enhttp://localhost:8080/your-app?lang=zh根據選擇的語言,頁面將顯示相應的歡迎消息。
通過以上步驟,你可以在Ubuntu上成功實現JSP的國際化。