상세 컨텐츠

본문 제목

한글 고민 끝 .. 한글 테스트 jsp, java

IT 세상/자바세상

by 이현민 (지후지율아빠) 2010. 2. 23. 20:08

본문


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

<%! private static java.text.SimpleDateFormat df =
    new java.text.SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
%>
<html>
<head>
<script language=javascript>
function getCookie(Name) {
 var search = Name + "=";
 if (document.cookie.length>0){
  offset = document.cookie.indexOf(search);
  if (offset != -1){
   offset += search.length;
   end = document.cookie.indexOf(";", offset);
   if (end == -1)
    end = document.cookie.length;
   return document.cookie.substring(offset, end);
  }
 }
}

</script>
<body>
<h2>한글 테스트 프로그램</h2>
<hr width=450 align=left>
<%
     String r_name = null;
     try{ r_name = request.getParameterValues("name")[0];}catch(Exception e){}
     String encoded_name = ( r_name == null ) ? null: new String(r_name.getBytes("8859_1"),"UTF-8");
  String dbencoded_name = ( r_name == null ) ? null: new String(encoded_name.getBytes("8859_1"),"UTF-8");
%><pre>
String name = request.getParameterValues("name")[0] : <b>[<%=  r_name %>] <-- Result !! </b>
new String(name.getBytes("8859_1"),"UTF-8")       : <b>[<%=  encoded_name %>]  <-- Result !!</b>
double encoding       : <b>[<%=  dbencoded_name %>]  <-- Result !!</b>
현재 시간: <%=  df.format(new java.util.Date()) %>
</pre>
<hr width=450 align=left>
<pre>
NOTE: &lt;%@ page contentType="text/html" %&gt;
      &lt;%@ page contentType="text/html;charset=utf-8" %&gt;
      위 두 방식을 반드시 모두 테스트 해 볼 것 !!

1. System.getProperty("file.encoding") : <b><%=  System.getProperty("file.encoding") %></b>
2. System.getProperty("default.client.encoding") : <b><%=  System.getProperty("default.client.encoding") %></b> (only IBM WebSphere)
   System.getProperty("client.encoding.override") : <b><%=  System.getProperty("client.encoding.override") %></b> (only IBM WebSphere)
3. request.getCharacterEncoding() : <b><%=  request.getCharacterEncoding() %></b>
4. JSP에 명시적으로 적혀있는 한글들....
5. &lt;%= "한글" 의 결과 : <b><%=  "한글" %></b>
6. "한글".getBytes() 의 결과:          <b><%
   byte[] bytes = "한글".getBytes();
   for(int i=0;i<bytes.length;i++) out.print(Integer.toHexString(bytes[i] & 0xff) + " ");
%></b>
   "한글".getBytes("8859_1") 의 결과:  <b><%
   bytes = "한글".getBytes("8859_1");
   for(int i=0;i<bytes.length;i++) out.print(Integer.toHexString(bytes[i] & 0xff) + " ");
%></b>
   "한글".getBytes("UTF-8") 의 결과: <b><%
   bytes = "한글".getBytes("UTF-8");
   for(int i=0;i<bytes.length;i++) out.print(Integer.toHexString(bytes[i] & 0xff) + " ");
%></b>

7. java.net.URLEncoder.encode("한글") 의 결과: <b><%=  java.net.URLEncoder.encode("한글") %></b>
   "%C7%D1%B1%DB" 이 나와야 함. 그렇지 않다면, 다음의 결과가
   이상하게 될 것임.(UTF-8에선 다를 수 있음)
   hangul.jsp?name=&lt;%= java.net.URLEncoder.encode("한글") %&gt; :
   <a href="hangul.jsp?name=<%=  java.net.URLEncoder.encode("한글") %>"
     >hangul.jsp?name=<%=  java.net.URLEncoder.encode("한글") %></a>  <---- Click !!
<%
  String h = "한글";
  String url = "hangul.jsp?name="+ java.net.URLEncoder.encode(h) ;
%>
[HTTP Form Test]</pre>
<table border=1>
<tr><td align=top>[1] GET method : </td><td><form method=GET action="hangul.jsp">
<input type=text size=10 name="name" value="한글">
<input type=submit value="GET방식으로 호출">
</td></tr></form>
<tr><td>[2] POST method: </td><td><form method=POST action="hangul.jsp">
<input type=text size=10 name="name" value="한글">
<input type=submit value="POST방식으로 호출">
</td></tr></form>
</table><pre>

----------------------------------
[Cookie 한글 테스트]

서비측 JSP에서 아래 방식으로 서로다른 쿠키를 세개 셋팅함
&lt;%
1.
  Cookie cookie = new Cookie(
    "mycookie",
    "한글");
  cookie.setPath("/");
  cookie.setMaxAge(60*60*1000);
  response.addCookie(cookie);

2.
  Cookie encoded_cookie = new Cookie(
    "encoded_mycookie",
    java.net.URLEncoder.encode("한글"));
  encoded_cookie.setPath("/");
  encoded_cookie.setMaxAge(60*60*1000);
  response.addCookie(encoded_cookie);

3.
  Cookie double_encoded_cookie = new Cookie(
    "double_encoded_cookie",
    java.net.URLEncoder.encode( new String("한글".getBytes(), "8859_1") ));
  double_encoded_cookie.setPath("/");
  double_encoded_cookie.setMaxAge(60*60*1000);
  response.addCookie(double_encoded_cookie);
%&gt;


<%
  Cookie cookie = new Cookie(
    "mycookie",
    "한글");
  cookie.setPath("/");
  cookie.setMaxAge(60*60*1000);
  response.addCookie(cookie);

  Cookie encoded_cookie = new Cookie(
    "encoded_cookie",
    java.net.URLEncoder.encode("한글"));
  encoded_cookie.setPath("/");
  encoded_cookie.setMaxAge(60*60*1000);
  response.addCookie(encoded_cookie);

  Cookie double_encoded_cookie = new Cookie(
    "double_encoded_cookie",
    java.net.URLEncoder.encode( new String("한글".getBytes(), "8859_1") ));
  double_encoded_cookie.setPath("/");
  double_encoded_cookie.setMaxAge(60*60*1000);
  response.addCookie(double_encoded_cookie);

%>


[위에서 셋팅한 Cookie 를 서버측에서 읽어보았을 때(두번째 호출부터 보일 것임)]
[request.getCookies()]
<%
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            for(int i=0; i<cookies.length; i++) {
                out.print(cookies[i].getName() + "=" + cookies[i].getValue());
                out.println( "(java.net.URLDecoder.decode(): " + java.net.URLDecoder.decode(cookies[i].getValue()) + ")");
            }
        }
%>

[위에서 셋팅한 Cookie 를 브라우져에서 JavaScript로 읽어보았을 때]
[JavaScript cookie]
(Server 에서 셋팅한 cookie를  브라우져의 JavaScript 로 읽어봤을 때)

<script language=javascript>
  document.writeln("getCookie('mycookie') : " + getCookie('mycookie'));
  document.writeln("escape(getCookie('mycookie')) : " + escape(getCookie('mycookie')));
  document.writeln("unescape(getCookie('mycookie')) : " + unescape(getCookie('mycookie')));
  document.writeln();

  document.writeln("getCookie('encoded_cookie') : " + getCookie('encoded_cookie'));
  document.writeln("escape(getCookie('encoded_cookie')) : " + escape(getCookie('encoded_cookie')));
  document.writeln("unescape(getCookie('encoded_cookie')) : " + unescape(getCookie('encoded_cookie')));
  document.writeln();

  document.writeln("getCookie('double_encoded_cookie') : " + getCookie('double_encoded_cookie'));
  document.writeln("escape(getCookie('double_encoded_cookie')) : " + escape(getCookie('double_encoded_cookie')));
  document.writeln("unescape(getCookie('double_encoded_cookie')) : " + unescape(getCookie('double_encoded_cookie')));

</script>
NOTE: function getCookie() is user defined javascript function.


<hr width=450 align=left>

RequestURL=<%=  HttpUtils.getRequestURL(request).toString() %>

[Request information]
request.getMethod()=<%=  request.getMethod() %>
request.getRequestURI()=<%=  request.getRequestURI() %>
request.getProtocol()=<%=  request.getProtocol() %>
request.getServletPath()=<%= request.getServletPath() %>
request.getPathInfo()=<%= request.getPathInfo() %>
request.getPathTranslated()=<%= request.getPathTranslated() %>
request.getCharacterEncoding()=<%= request.getCharacterEncoding() %>
request.getQueryString()=<%= request.getQueryString() %>
request.getContentLength()=<%= request.getContentLength() %>
request.getContentType()=<%= request.getContentType() %>
request.getServerName()=<%= request.getServerName() %>
request.getServerPort()=<%= request.getServerPort() %>
request.getRemoteUser()=<%= request.getRemoteUser() %>
request.getRemoteAddr()=<%= request.getRemoteAddr() %>
request.getRemoteHost()=<%= request.getRemoteHost() %>
request.getAuthType()=<%= request.getAuthType() %>

[request.getHeaderNames()]
<%
  java.util.Enumeration enum1 = request.getHeaderNames();
  while(enum1.hasMoreElements()){
        String key = (String)enum1.nextElement();
        String value = request.getHeader(key);
        out.println(key + "=" + value);
  }
%>

[request.getParameterNames()]
<%
  enum1 = request.getParameterNames();
  while(enum1.hasMoreElements()){
        String key = (String)enum1.nextElement();
        String value = request.getParameter(key);
        out.println(key + "=" + value);
  }
%>


[request.getAttributeNames()]
<%
        enum1 = request.getAttributeNames();
        while(enum1.hasMoreElements()) {
            String key = (String)enum1.nextElement();
            String value = request.getAttribute(key).toString();
            out.println(key + "=" + value );
        }
%>


[request.getSession(false)]
<%
//HttpSession session = request.getSession(false);
if(session != null) {
%>
session.getId():<%= session.getId() %>
session.getLastAccessedTime(): <%=  new java.util.Date(session.getLastAccessedTime()).toString() %>
session.getCreationTime():<%= new java.util.Date(session.getCreationTime()).toString() %>
<%
    String mechanism = "unknown";
    if(request.isRequestedSessionIdFromCookie()) {
 mechanism = "cookie";
    }
    else if(request.isRequestedSessionIdFromURL()) {
 mechanism = "url-encoding";
    }
%>Session-tracking mechanism:<%=  mechanism %>
<%
    String[] vals = session.getValueNames();
    if(vals != null) {
 for(int i=0; i<vals.length; i++) {
     String name = vals[i];
     out.println(" " + name + ": " + session.getValue(name));
 }
    }
}
%>


[System Properties]
<%
        java.util.Properties props = System.getProperties();
        enum1 = props.keys();
        while(enum1.hasMoreElements()){
            String key = (String)enum1.nextElement();
            String value = (String)props.get(key);
            out.println(key + "=" + value);
        }
%>

file.encoding=<%= System.getProperty("file.encoding") %>
[WebSphere Properties]
default.client.encoding=<%= System.getProperty("default.client.encoding") %>
client.encoding.override=<%= System.getProperty("client.encoding.override") %>

<hr width=450 align=left>
WonYoung Lee. javaservice@hanmail.net, lwy@kr.ibm.com
</pre></body></html>

반응형

관련글 더보기