[JAVA]한글 인코딩 테스트 해보고자 할때 -_-;

Programming 2010.01.20 21:06
String originalFileName ="한글!!! 한글!! abc#@$$";
System.out.println("====org=====");
System.out.println(originalFileName);
System.out.println("====8859-1=====");
System.out.println(new String( originalFileName.getBytes( "8859_1"), "KSC5601"));
System.out.println(new String( originalFileName.getBytes( "8859_1"), "EUC-KR"));
System.out.println(new String( originalFileName.getBytes( "8859_1"), "UTF-8"));
System.out.println("====KSC5601=====");
System.out.println(new String( originalFileName.getBytes( "KSC5601"), "8859_1"));
System.out.println(new String( originalFileName.getBytes( "KSC5601"), "EUC-KR"));
System.out.println(new String( originalFileName.getBytes( "KSC5601"), "UTF-8"));
System.out.println("====EUC-KR=====");
System.out.println(new String( originalFileName.getBytes( "EUC-KR"), "8859_1"));
System.out.println(new String( originalFileName.getBytes( "EUC-KR"), "KSC5601"));
System.out.println(new String( originalFileName.getBytes( "EUC-KR"), "UTF-8"));
System.out.println("====UTF-8=====");
System.out.println(new String( originalFileName.getBytes( "UTF-8"), "KSC5601"));
System.out.println(new String( originalFileName.getBytes( "UTF-8"), "8859_1"));
System.out.println(new String( originalFileName.getBytes( "UTF-8"), "EUC-KR"));

당췌 시스템에 맞는 인코딩이 뭔지 모르겠다 할 때...
한번쯤 이렇게 코딩하고 테스트 해보시면 시스템에 맞는 인코딩 변환을 찾을수 있을겁니다.ㅋ

----- 추가 내용. ------

그것보단 일단 근본적인 문제를 일으키는 원인은...

서버 인코딩, 톰켓의 설정, application의 설정을 봐야함.

http://wiki.apache.org/tomcat/FAQ/CharacterEncoding

톰켓은 기본적으로 GET parameter에 대해서 ISO-8859-1 인코딩을 씀.

Tomcat will use ISO-8859-1 as the default character encoding of the entire URL, including the query string ("GET parameters").


서버가 만약 UTF-8 설정되있고, application encoding이 UTF-8 이라고 한다면

톰켓의 server.xml에 설정을 잡아준다.

Set URIEncoding="UTF-8" on your <Connector> in server.xml


그러면 일단 한글은 잘 될거임. ㅇㅇ



저작자 표시 비영리 변경 금지
신고

[Flex]Encoding problem when using URLVariables

Programming/Flex 2009.04.02 00:35
URLVariables를 통해서 파라미터를 셋팅하고, navigateToURL이나 URLLoader를 통해서 한글 데이터를 전송하고자 할 때, 한글 파라미터 값이 깨지는 경우가 발생합니다.

Server side에서 갖가지 인코딩을 다 적용해 보았으나 죄다 실패!
Flex에서 URLRequest의 contextType을 죄다 변경해 보았으나 역시 실패!

그래서 결국 생각해낸 방법이 Base64를 이용하는 것입니다.-_-;;
근본적인 해결책은 아니더라도... 나쁘진 않은 방법이긴 하죠.-ㅅ-;

<test.mxml>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
          <![CDATA[
              import flash.net.navigateToURL;
              import mx.utils.Base64Decoder;
              import mx.utils.Base64Encoder;
              private function finishSubmit(event:Event):void
            {
               
                var request:URLRequest = new URLRequest("/test.jsp");
                var param:URLVariables = new URLVariables();
                var be:Base64Encoder = new Base64Encoder();
                var bd:Base64Decoder = new Base64Decoder();
                be.encodeUTFBytes(t.text);
                en.text = be.toString();
                bd.decode(en.text);
                de.text = bd.flush().toString();
               
                request.method = URLRequestMethod.POST;
                request.data = param;
                param.txt = en.text;
                param.undecodetxt = t.text;
                var ul:URLLoader = new URLLoader();
                ul.dataFormat = URLLoaderDataFormat.VARIABLES;
                ul.load(request); // test.jsp로 리퀘스트가 전송됩니다.
               
               
            }
          ]]>
      </mx:Script>

    <mx:Panel title="LineChart and AreaChart Controls Example"
        height="100%" width="100%" layout="absolute">
        <mx:Button x="61" y="105" label="Button" click="finishSubmit(event)"/>
        <mx:Label x="61" y="37" id="t" text="한글 텍스트...."/>
        <mx:TextArea x="50" y="201" width="267" height="196" id="en"/>
        <mx:TextArea x="352" y="189" width="382" height="197" id="de"/>
    </mx:Panel>

</mx:Application>


참으로 귀찮았나 봅니다.-_-;; 암튼 위 코드를 실행하면 아래와 같은 화면이 실행됩니다.
버튼을 누르면 한글 스트링을 encoding, decoding합니다.
그리고 test.jsp로 전송도 하구요.

<test.jsp>
<%@ page language="java" contentType="text/html; charset=euc-kr"
    pageEncoding="UTF-8"   %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String txt = request.getParameter("txt");
String undecodetxt = request.getParameter("undecodetxt");
System.out.println(undecodetxt);
System.out.println(txt);
System.out.println(Base64Coder.decodeString(txt));

%>
</body>
</html>

<Base64Coder.java : 출처 (http://www.source-code.biz/snippets/java/2.htm)>
/**
* A Base64 Encoder/Decoder.
*
* <p>
* This class is used to encode and decode data in Base64 format as described in RFC 1521.
*
* <p>
* This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br>
* It is provided "as is" without warranty of any kind.<br>
* Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br>
* Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br>
*
* <p>
* Version history:<br>
* 2003-07-22 Christian d'Heureuse (chdh): Module created.<br>
* 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br>
* 2006-11-21 chdh:<br>
* &nbsp; Method encode(String) renamed to encodeString(String).<br>
* &nbsp; Method decode(String) renamed to decodeString(String).<br>
* &nbsp; New method encode(byte[],int) added.<br>
* &nbsp; New method decode(String) added.<br>
*/

public class Base64Coder {

// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i=0;
for (char c='A'; c<='Z'; c++) map1[i++] = c;
for (char c='a'; c<='z'; c++) map1[i++] = c;
for (char c='0'; c<='9'; c++) map1[i++] = c;
map1[i++] = '+'; map1[i++] = '/'; }

// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i=0; i<map2.length; i++) map2[i] = -1;
for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }

/**
* Encodes a string into Base64 format.
* No blanks or line breaks are inserted.
* @param s a String to be encoded.
* @return A String with the Base64 encoded data.
*/
public static String encodeString (String s) {
return new String(encode(s.getBytes())); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted.
* @param in an array containing the data bytes to be encoded.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode (byte[] in) {
return encode(in,in.length); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted.
* @param in an array containing the data bytes to be encoded.
* @param iLen number of bytes to process in <code>in</code>.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode (byte[] in, int iLen) {
int oDataLen = (iLen*4+2)/3; // output length without padding
int oLen = ((iLen+2)/3)*4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '='; op++;
out[op] = op < oDataLen ? map1[o3] : '='; op++; }
return out; }

/**
* Decodes a string from Base64 format.
* @param s a Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static String decodeString (String s) {
return new String(decode(s)); }

/**
* Decodes a byte array from Base64 format.
* @param s a Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static byte[] decode (String s) {
return decode(s.toCharArray()); }

/**
* Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded data.
* @param in a character array containing the Base64 encoded data.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static byte[] decode (char[] in) {
int iLen = in.length;
if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iLen-1] == '=') iLen--;
int oLen = (iLen*3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
int o0 = ( b0 <<2) | (b1>>>4);
int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
int o2 = ((b2 & 3)<<6) | b3;
out[op++] = (byte)o0;
if (op<oLen) out[op++] = (byte)o1;
if (op<oLen) out[op++] = (byte)o2; }
return out; }

// Dummy constructor.
private Base64Coder() {}

} // end class Base64Coder

<결과 System.out>
한글 텍스트....
7ZWc6riAIO2FjeyKpO2KuC4uLi4=
한글 텍스트....

<Http Request Header에 찍히는 Parameter 정보>
txt=7ZWc6riAIO2FjeyKpO2KuC4uLi4%3D&undecodetxt=%ED%95%9C%EA%B8%80%20%ED%85%8D%EC%8A%A4%ED%8A%B8%2E%2E%2E%2E

네~ 됩니다.

플렉스는 아직 한글을 싫어라 합니다. 젠장.-ㅅ-;;

혹시나 서버사이드에서 인코딩 쉽사리 전송된 사례가 있다면 공유 부탁드립니다.(__)*


저작자 표시 비영리 변경 금지
신고


티스토리 툴바