struts 1.x 国际化

1. 准备struts资源文件,注意使用UTF-8编码

资源配置例子如下,左图是简体中文资源,右图是英文资源。根据实际需要,选用其中一种语言作为默认资源。

  

 

2. 在struts-config配置文件中添加如下配置

parameter参数填写的是默认资源文件的文件名,包含路径,不包含后缀名。上图配置表示资源文件放在程序根目录下。

 

3. 页面添加切换语言的超链接

 

 4. 编写切换语言的action

 1 import org.apache.struts.Globals;
 2 import org.apache.struts.action.Action;
 3 import org.apache.struts.action.ActionForm;
 4 import org.apache.struts.action.ActionForward;
 5 import org.apache.struts.action.ActionMapping;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import java.util.Locale;
10 
11 /**
12  * @author LW_Fung
13  */
14 public class LanguageAction extends Action {
15 
16     @Override
17     public ActionForward execute(ActionMapping mapping, ActionForm form,
18                                  HttpServletRequest request, HttpServletResponse response) {
19         String lang = request.getParameter("lang");
20         Locale curLocale;
21         if ("zh".equals(lang)){
22             curLocale = new Locale("zh", "CN");
23         } else if ("en".equals(lang)) {
24             curLocale = new Locale("en");
25         } else {
26             curLocale = Locale.getDefault();
27         }
28         request.getSession().setAttribute(Globals.LOCALE_KEY, curLocale);
29         this.setLocale(request, curLocale);
30         return mapping.findForward("index");
31     }
32 }

  

5. struts-config配置文件中配置上述action

 

 6. 在页面使用bean:message标签引用资源

 

7. 最终效果如图

 

posted @ 2017-10-22 12:01  LW_FUNG  阅读(93)  评论(0)    收藏  举报