---
title: "struts 国际化乱码"
author: "endual"
date: "2012-02-25T09:15:57Z"
tags: []
categories: ["开源软件"]
slug: "struts"
draft: false
lastmod: "2012-02-25T09:26:44Z"
id: 1423505
url: "https://endual.iteye.com/blog/1423505"
---

差不多半年没复习框架了，都在搞论文和打基础，什么算法和数据结构，还看操作系统啥的，不知道这些

在实际的开发中能用到多少。

   大半年不用struts2连个国际化都不怎么写了，呵呵，按照书上居然弄出了，网上一查马上就搞好了，然而，

居然有出现了中文乱码，真是可恶啊。

 

   下面是解决的办法吧：

 

 1.  首先在struts.xml中配置好国家化资源文件的开头的名字

 

 

```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="false" />


    <constant name="struts.custom.i18n.resources" value="message"/>
   
    <package name="default" extends="struts-default" >
        <action name="index" class="endual.iteye.action.Login">
            <result name="success" >hello.jsp</result>
        </action>
    </package>

    <!-- Add packages here -->

</struts>
```

 

 

 2.资源文件的名字要取好  &lt;constant name="struts.custom.i18n.resources" value="message"/&gt;

 

   这个message就是我们要配置资源文件的开头的名字，你总要告诉框架，我国际化的资源文件的名字是对吧。

然后我们在src下创建两个资源文件，中文一个，英文一个，就是每一种语言一个资源文件

 

   message\_zh\_CN.properties

 

```
HelloWorld = 世界你好 !
```

 

 

   message\_en\_US.properties

 

```
HelloWorld = Hello World !
```

 

 

忘记说了，我们要把资源文件的编码改成支持中文的GBK，什么国家的语言，改成支持什么国家的编码格式吧。要不都无法保存。

 

3.JSP页面的测试：

 

 

```
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'test.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    
    x<s:property  value="%{getText('HelloWorld')}"/>x
    
   <!--   <s:textfield name="name" label="%{getText(HelloWorld)}"></s:textfield> -->
    
  </body>
</html>
```

 

 

4.启动tomcat，哎呀，你发现了乱码对吧，呵呵。没关系，很容易解决的。

 

我们要记住了，资源文件中中文要转成asc嘛，貌似拼错了，但是你懂的，就是java语言本身支持的那么编码。

java有工具，在bin目录下，但是，伟大的中国人还是会用代码来解决，比较dos下去打开输入是麻烦的。

 

 

\--------------------------

5.将中文的字符转成ascii编码，用下面的代码

 

 

```
package util;  
  
/** 
 * native2ascii.exe Java code implementation. 
 *  
 * @author 
 * @version 1.0 
 */  
public class Native2AsciiUtils {  
  
    /** 
     * prefix of ascii string of native character 
     */  
    private static String PREFIX = "\\u";  
  
    /** 
     * Native to ascii string. It's same as execut native2ascii.exe. 
     *  
     * @param str 
     *            native string 
     * @return ascii string 
     */  
    public static String native2Ascii(String str) {  
        char[] chars = str.toCharArray();  
        StringBuilder sb = new StringBuilder();  
        for (int i = 0; i < chars.length; i++) {  
            sb.append(char2Ascii(chars[i]));  
        }  
        System.out.println(sb.toString()) ;
        return sb.toString();  
    }  
  
    /** 
     * Native character to ascii string. 
     *  
     * @param c 
     *            native character 
     * @return ascii string 
     */  
    private static String char2Ascii(char c) {  
        if (c > 255) {  
            StringBuilder sb = new StringBuilder();  
            sb.append(PREFIX);  
            int code = (c >> 8);  
            String tmp = Integer.toHexString(code);  
            if (tmp.length() == 1) {  
                sb.append("0");  
            }  
            sb.append(tmp);  
            code = (c & 0xFF);  
            tmp = Integer.toHexString(code);  
            if (tmp.length() == 1) {  
                sb.append("0");  
            }  
            sb.append(tmp);  
          
            return sb.toString();  
        } else {  
        	
            return Character.toString(c);  
        }  
    }  
  
    /** 
     * Ascii to native string. It's same as execut native2ascii.exe -reverse. 
     *  
     * @param str 
     *            ascii string 
     * @return native string 
     */  
    public static String ascii2Native(String str) {  
        StringBuilder sb = new StringBuilder();  
        int begin = 0;  
        int index = str.indexOf(PREFIX);  
        while (index != -1) {  
            sb.append(str.substring(begin, index));  
            sb.append(ascii2Char(str.substring(index, index + 6)));  
            begin = index + 6;  
            index = str.indexOf(PREFIX, begin);  
        }  
        sb.append(str.substring(begin));  
        return sb.toString();  
    }  
  
    /** 
     * Ascii to native character. 
     *  
     * @param str 
     *            ascii string 
     * @return native character 
     */  
    private static char ascii2Char(String str) {  
        if (str.length() != 6) {  
            throw new IllegalArgumentException(  
                    "Ascii string of a native character must be 6 character.");  
        }  
        if (!PREFIX.equals(str.substring(0, 2))) {  
            throw new IllegalArgumentException(  
                    "Ascii string of a native character must start with \"\\u\".");  
        }  
        String tmp = str.substring(2, 4);  
        int code = Integer.parseInt(tmp, 16) << 8;  
        tmp = str.substring(4, 6);  
        code += Integer.parseInt(tmp, 16);  
        return (char) code;  
    }  
  
} 
```

 

 

main类

 

```
package util;

import java.util.Scanner;

public class MainApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in) ;
		String str = in.next(); 
		
		//Native2AsciiUtils.ascii2Native(str) ;
		Native2AsciiUtils.native2Ascii(str) ;
		

	}

}
```

 

 

 

  然后运行程序，把世界你好的中文转成------》》》》》》》》   

 

```
\u4e16\u754c\u4f60\u597d 
```

就OK了，然后填写到资源文件夹中。

 

这样中文就不会乱码了。

 

\-----------------------------------------

```
假设我们在HelloAction调用了getText那么它会执行以下的操作的

1.查找HelloAction.xx.xx.properties文件中
2.查找HelloAction实现的接口，以及与接口同名的资源文件MyInterface.propreties
3.查找HelloAction的弗雷parentAction的properties文件，文件名为parentAction.properties
4.判断当前HelloAction是否是实现了接口ModelDriven 如果是的，那么就调用getModel方法获得对象
  查找与其同名的资源文件
5.查找当前包下的packaga.paoperties
6.查找到前包的父包，直到顶层包
7.在值栈中查找名为helloworld的属性
8.查找在struts.properties配置的默认的资源文件
9.输出结果
```

 

 

 

\-----------------------------

 

不知道开发中用到的是什么编码格式，反正GBK是支持英语和中文的，貌似实际的开发中UTF-8用的很多吧