JSP

[펌] MySQL JDBC JSP 저장 로드시 한글깨짐 현상 해결법 정리

십억10 2009. 4. 6. 13:38

JSP와 MySQL 그리고 JDBC를 처음 사용하면서 DB에 데이터를 저장하거나 불러올때 한글깨짐 현상때문에 해결하느라 고생한 경험이 있습니다. (Oracle도 연결부분의 설정을 제외하고는 동일합니다.)

같은문제로 고민하는 분들께 도움이되도록
그때 해 놓았던 한글깨짐 현상과 관련된 설정들을 상황별로 공개합니다.

Tomcat 6.0


<conf/server.xml>

<!-- Tomcat TMJ Context -->

  <Context path="" docBase="c:\mysite" debug="1" reloadable="true" crossContext="true"> 

  <Resource name="jdbc/mysiteDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="5000" username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mysite?characterEncoding=euckr"/>


<conf/web.xml>

<servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>


이것만으로 안될경우 conf 폴더에 context.xml 을 만들어 봅니다.

<context.xml>

<?xml version='1.0' encoding='utf-8'?>
<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>


jsp 페이지 최상단의 charset 설정은 기본

<%@ page language="java" import="java.sql.*, java.lang.*, java.util.* " contentType= "text/html;charset=euc-kr"%>


post로 전송시 제대로 안나올시 코드 추가

//한글이 정상출력이 안된다면 아래 코드를 추가
<% request.setCharacterEncoding("euc-kr"); %>

//폼에서 전송받을시 문제가 생긴다면 .trim()을 사용
String title = request.getParameter("title").trim();



get 파라메타로 넘어온 값 변환 코드와 사용 예

<변환코드>

<%!
//한글처리
public static String kor2Db(String sToDb) throws UnsupportedEncodingException{
 if (sToDb == null) return null;
 else return new String(sToDb.getBytes("8859_1"),"EUC-KR");
 }
%>

<%!
public static String Db2kor(String DbTos) throws UnsupportedEncodingException{
 if (DbTos == null) return null;
 else return new String(DbTos.getBytes("EUC-KR"),"8859_1");
 }
%>

<출력 예>

<p align="left"><input type="text" name="subject" size="46" maxlength="100" value="<%=kor2Db(subject)%>">

<textarea name="contexts" class="textarea" style="width:580;height:230;" rows="1" cols="20"><%=kor2Db(contexts)%></textarea>


파일 및 이미지 업로드시 한글파일명 저장 예제

<한글 파일명 업로드>

<%@ page import="java.net.*,java.io.*,java.sql.*,java.util.*,javax.naming.*,javax.sql.DataSource" %>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>


<%!
 //null체크를 위한 function으로 nullpoint에러를 잡는다.
 public static String nullcheck(String str) throws Exception {

        if (str == null){
            return "";
        }else{
          return str;     // 넘어온 Stirng 을 그대로 다시 return
      }
     }
%>

String savePath="C:/mysite/upload/image";
int sizeLimit=1024*1024*5;


MultipartRequest multi = new MultipartRequest(request,savePath,sizeLimit, "EUC-KR", new DefaultFileRenamePolicy());

String subject=nullcheck(multi.getParameter("subject"));
String contexts=nullcheck(multi.getParameter("contexts"));

String fileName1 = nullcheck(multi.getFilesystemName("add_file1"));
String fileName2 = nullcheck(multi.getFilesystemName("add_file2"));
String fileName3 = nullcheck(multi.getFilesystemName("add_file3"));
String fileName4 = nullcheck(multi.getFilesystemName("add_file4"));
String fileName5 = nullcheck(multi.getFilesystemName("add_file5"));
String fileName6 = nullcheck(multi.getFilesystemName("add_file6"));

int message=0;
String sql="";
 
sql="insert into imageupload (subject,context,image1,image2,image3,image4,image5,image6 ) "; 
sql+="value('"+subject+"','"+contexts+"','"+fileName1+"','"+fileName2+"','"+fileName3+"','"+fileName4+"',
'"+fileName5+"','"+fileName6+"')";

%>
<%@ include file="../include/try.jsp" %>
<%
      
      message=stmt.executeUpdate(sql);
   stmt.close();
%>

<%@ include file="../include/catch.jsp" %>
<%
if( message > 0 )
{
%>
<script language="javascript">
   alert('정상적으로 처리 되었습니다.');
   //location.href="./imageUpload.jsp";
   location.href="./imageUploadList.jsp";
</script>
<%
}
else
{
%>
   <script language="javascript">
 alert('입력오류 에러입니다.');
    history.go(-1);
</script>

<%
}
%>

 
한글 파일명 다운로드 코드 예제

<한글 파일명 다운로드>

<%@ page contentType="text/html; charset=euc-kr" pageEncoding="EUC-KR" import="java.io.*"%>
<% 

 //주소와 파일이름 가져오기 (fileName는 "EUC-KR" 방식으로 인코딩된 파라메타)
 String fileName = request.getParameter("fileName");

 String uploadfilePath = "C:/mysite/upload/";
 //또는 아래 사용
 //String filePath = request.getRealPath("/")+"uploadFile/";
 //System.out.println(filePath);
 
 //응답 헤더의 Content-Type을 세팅한다.
 response.setContentType("application/x-msdownload");
 
//한글파일 Download 시에 에러가 나는게 이 코드가 빠져 있어서 그런거 같은디..^^
String convName1 = new String(fileName.getBytes("euc-kr"),"8859_1"); 

 //Content-Disposition 헤더에 파일 이름 세팅.
 response.setHeader("Content-Disposition", "attachment;filename=" + convName1 + ";");

// 파일 객체생성
// fileName은 "8859_1" 방식 인코딩
File file = new File(uploadfilePath+fileName);
 
 // 사용자에게 보내주기 위해 스트림객체 생성
 byte b[] = new byte[(int)file.length()];   
 if (file.length() > 0 && file.isFile()) // 0byte이상이고, 해당 파일이 존재할 경우
 {
   BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file)); 

   // 인풋객체생성
   BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream()); 

  // 응답객체생성   
  int read = 0;
  try {
   while ((read = fin.read(b)) != -1){
       outs.write(b,0,read);
   }
   outs.close();
   fin.close();
  } catch (Exception e) {
   System.out.println("download error : " + e.getMessage());
  } finally {
   if(outs!=null) outs.close();
   if(fin!=null) fin.close();
  }
 }  
   
%>


도움이 되었길 바랍니다. ^^

 

출처 : http://mixiworld.tistory.com/78?srchid=BR1http%3A%2F%2Fmixiworld.tistory.com%2F78