SpringMVC 國際化問題


1、首先在src文件下添加3個properties文件

  a、message.properties

1 message.username=UserName
2 message.password=Password

  b、message_en.properties

1 message.username=UserName
2 message.password=Password

  c、message_zh.properties

1 message.username=\u7528\u6237\u540D
2 message.password=\u5BC6\u7801

 

2、配置spring-mvc.xml文件

1 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
2     <!-- 指定文件基名 -->
3      <property name="basename" value="message"/>
4      <!-- 當沒有找到資源文件時,用這基名文件 -->
5      <property name="useCodeAsDefaultMessage" value="true" />    
6  </bean>

  這里配置屬性userCodeAsDefaultMessage=true。意思當在其他語言區域里,沒有找到對應的國際化文件。比如日語區、韓語區等。默認使用message.properties文件。當為false時,顯示有問題。

 

3、配置Controller

 1 @Controller
 2 public class UserController {
 3 
 4     @RequestMapping("/updateUser")
 5     public String update(){
 6 
 7         return "success";
 8     }
 9     
10 }

 

4、Jsp頁面

  要做jsp頁面中使用國際化信息。需要添加一個fmt標簽。該標簽在JSTL標簽表中。添加方式

1 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 

  index.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 3 
 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 5 <html>
 6   <head>
 7     <title>My JSP 'hello.jsp' starting page</title>
 8   </head>
 9   
10   <body>
11     
12     <fmt:message key="message.username"/><input type="text" name="username" /><br/>
13     <fmt:message key="message.password"/><input type="text" name="password" /><br/>
14   </body>
15 </html>

 

  hello.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 3 
 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 5 <html>
 6   <head>
 7     <title>My JSP 'hello.jsp' starting page</title>
 8   </head>
 9   
10   <body>
11     
12     <fmt:message key="message.username"/><input type="text" name="username" /><br/>
13     <fmt:message key="message.password"/><input type="text" name="password" /><br/>
14   </body>
15 </html>

 

  我們通過url訪問success.jsp頁面。

  訪問地址:http://localhost:8080/springmvc-1/updateUser

 

  我們訪問index.jsp頁面http://localhost:8080/springmvc-1

  結果出現這樣的結果

 

為什么JSP頁面都是一樣的。為什么結果不一樣呢?

  原因是index.jsp頁面可以直接被訪問到,而success.jsp頁面在WEB-INF下面,不能夠直接訪問,需要通過servlet轉發的方式才夠訪問。在SpringMVC中,DispatcherServlet前端控制器,攔截了所有請求,對http://localhost:8080/springmvc-1/updateUser訪問。交個SpringMVC去處理。而在spring-mvc.xml配置了ResourceBundleMessageSource,所以在success頁面中可以使用國際化信息。

   綜上所述:要使用基於頁面的國際化信息,需要使用轉發的方式才能生效。

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM