天天看点

Spring + ExtJs4.x 国际化 (附:中文代码过滤Demo)

一、最近系统要增加国际化的功能,首先要把代码中所有的中文copy出来,交付翻译;

以下是自己写的过滤中文Demo:

public static void main(String[] args) {
		Scanner.scanning("D:\\test");
	}
           
public class Scanner {

	/**
	 * 递归遍历文件
	 */
	public static List<File> getFile(File f) {
		File[] allfiles = f.listFiles();
		List<File> filelist = new ArrayList<File>();
		for (int i = 0; i < allfiles.length; i++) {
			if (allfiles[i].isDirectory()) {
				filelist.addAll(getFile(allfiles[i]));
			} else {
				filelist.add(allfiles[i]);
			}
		}
		return filelist;
	}

	/**
	 * 开始解析
	 */
	public static void scanning(String path) {
		System.out.println("*************开始解析:" + path + "*****************");
		List<File> filelist = getFile(new File(path));
		for (File file : filelist) {
			Analyzer.analyze(file);
		}
		System.out.println("************路径:" + path + "下的文件解析完毕**********");
	}

}

           
public class Analyzer {

	private static String encoding = "UTF-8";

	public static void analyze(File f) {
		if (f.isFile() && f.exists()) {
			String pstr = "\"([^\"|[\u4e00-\u9fa5]]+)\"";
			if (f.getName().endsWith(".js")) {
				pstr = "\'([[\u4e00-\u9fa5]]+)\'";// 匹配 ''之间的中文内容
			} else if (f.getName().endsWith(".java")) {
				pstr = "\"([[\u4e00-\u9fa5]]+)\"";// 匹配 " " 之间的中文内容
			} else {
				return;
			}
			try {
				FileInputStream fileInStr = new FileInputStream(f);
				InputStreamReader read = new InputStreamReader(fileInStr,
						encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				while (bufferedReader.ready()) {
					String rowStr = bufferedReader.readLine();
					if (rowStr.startsWith("//"))
						continue;
					Pattern p = Pattern.compile(pstr);
					Matcher m = p.matcher(rowStr);
					if (m.find()) {
						for (int i = 0; i < m.groupCount(); i++) {
							System.out.println(m.group(i));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
           

正则表达式不是很懂,摸索着写出来的,测试无误,高手可能会有更好的写法,呵呵!

翻译好后,开始建语言资源文件

二、Spring的国际化

1.配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  
<beans>  
   
       <bean id="messageSource"  class="org.springframework.context.support.ResourceBundleMessageSource">  
   
      <property name="basename" value="messages"/>  
  
      </bean>  
   
       <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>  
     
</beans>  
           

2.在src根目录下面创建4个资源文件,分别是:

messages_zh.properties
main.title=你好

messages_en.properties
main.title=Hello World!

messages_ja.properties
main.title=こんにちは

messages_ko.properties
main.title=안녕하십니까
           

3.JSP页面的写法

<%@ page language="java"  pageEncoding="UTF-8"%>  
    <%@ taglib prefix="spring" uri="WEB-INF/lib/spring.tld"%>  
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    <html>  
      <head>  
        <title>Spring国际化</title>  
      </head>  
      <body>  
       
        <spring:message code="main.title" /><br>  
      
        <input type="button" value="<spring:message code="main.title" />"/><br>  
      
      </body>   
      
    </html>  
           

4.在web.xml加入

<context-param>  
      <param-name>contextConfigLocation</param-name>  
      <param-value>  
       classpath*:/applicationContext*,classpath*:META-INF/applicationContext*.xml  
      </param-value>  
     </context-param>  
     <listener>  
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
     </listener>  
           

注意事项:

1:用hibernate3.0,连接Mysql5.0数据库。

如果用hibernate.properties配置文件

hibernate.connection.url jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8

如果用hibernate.cfg.xml配置文件

jdbc:mysql://localhost:3306/test?useUnicode=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;mysqlEncoding=utf8

2:页面的编码方式,应该选用utf-8

<%@ page language="java"  pageEncoding="UTF-8"%>

3:创建的数据库的编码方式也应该选用utf-8,以及表,字段的编码方式都应选用utf-8

注意以上3点就可以解决国际化时,所出现的页面显示乱码问题,以及插入韩语时,出现的data too long for column问题.

这样用Spring国际化的jsp页面就做好了,此种方法是自动默认当前用户的语言,比如客户端是日语系统,就自动寻找messages_ja.properties资源文件,是英语系统,就自动寻找messages_en.properties资源文件。

三、ExtJs4.X的国际化

1、取得浏览器语言设定

  request.setAttribute("browserLang", request.getLocale().toString());

2、引入国际化文件(注意:在ext-all.js文件引入后再引入国际化文件才有效)

  <script type="text/javascript" src="ext/source/locale/ext-lang-<%=browserLang %>.js"></script>  

3、指定正确的页面字符集

  <%@ page contentType="text/html; charset=UTF-8" language="java"%>

ext-lang-zh_CN.js的内容如下:

var myProject = {};  
myProject.string = {};  
myProject.string.title = '我的表单';  
myProject.string.lable = '本地化'; 
           

MyForm.js内容如下:

Ext.define('MyApp.view.MyForm', {  
    extend: 'Ext.form.Panel',  
  
    height: 250,  
    width: 400,  
    bodyPadding: 10,  
    title: myProject.string.title,  // 这里是重点
  
    initComponent: function() {  
        var me = this;  
  
        Ext.applyIf(me, {  
            items: [  
                {  
                    xtype: 'label',  
                    text: myProject.string.lable  // 这里是重点
                }  
            ]  
        });  
  
        me.callParent(arguments);  
    }  
  
});  
           

其他的语言文件也这样写就可以了。

至此,国际化的工作OK!