[실습1-2][memo] JDBC 접속 설정 및 Utility Class 추가, 한글 처리

[01] JSP Server 페이지 제작
    - Eclipse setting
      Project Type: Dynamic Web Project
      Project Name: www_flex/WebContent/memofxjsp


1. JDBC 접속 설정 및 Utility Class 추가(한글 변환)

>>>>> Utility.java

package www.utility;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public class Utility {
    
    public static Date setDate(String date){
        Date currentTime = new Date();
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
        try{
            currentTime=sd.parse(date);
        }catch(Exception e){
        } 
        // System.out.println(date);        
        return currentTime;
    }

    public static String progress(String enddate){
        java.util.Date nowtime = new java.util.Date();
        java.util.Date endtime = setDate(enddate);
        
        //System.out.println("nowtime: " + nowtime.toLocaleString());
        //System.out.println("endtime: " + nowtime.toLocaleString());
        String progress = null;
        
        if(nowtime.after(endtime) == true){
            progress = "종료";
        }else{
            progress = "진행";
        }
        
        return progress;
    }
    

    /**
     * 천단위마다 컴마를 출력합니다.
     * @param price 금액
     * @return 컴마가 포함된 문자열
     */
    public static String comma(int price){
        DecimalFormat comma = new DecimalFormat("###,##0");
        String cs = comma.format(price);
        
        return cs;
    }

    /**
     * 천단위마다 컴마를 출력합니다.
     * @param price 금액
     * @return 컴마가 포함된 문자열
     */
    public static String comma(long price){
        DecimalFormat comma = new DecimalFormat("###,##0");
        String cs = comma.format(price);
        
        return cs;
    }
    
    /**
     * null 문자를 공백 문자로 변경합니다.
     * @param str 검사할 문자열
     * @return null 값을 가지고 있는 객체는 공백 문자열로 리턴됨
     */    
    public static String checkNull(String str){
        if ( str == null){
            return "";
        }else{
            return str;
        }
    }
   
    /**
     * 오늘 날짜를 문자열로 리턴합니다.
     * @return
     */
    public static String getCalendarDay(){
        String str="";
        Calendar cal = Calendar.getInstance();
        str = "" + cal.get(Calendar.DATE); //날짜
        
        return str;
    }

    /**
     * yyyy-mm-dd 형식의 날짜를 리턴합니다.
     * @return 2008-01-30 형식의 문자열 리턴
     */
    public static String getDate(){
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        
        String date = sd.format(new Date());

        // System.out.println(date);        
        return date;
    }
    
    /**
     * 내용중에 특수문자 표현을 위해 HTML 특수문자로 변환합니다.
     */
    public static String getConvertChar(String str){
        for(int i=0; i < str.length(); i++){
            if(str.charAt(i) =='<'){
                str=str.substring(0, i) + "&lt;" + str.substring(i+1, str.length());
                i=i+4; //1자가 3자로 변환됨으로 +4을 합니다.
            }else if(str.charAt(i) == '>'){
                str=str.substring(0, i) + "&gt;" + str.substring(i+1, str.length());
                i=i+4;
            }else if(str.charAt(i) == '&'){
                str=str.substring(0, i) + "&amp;" + str.substring(i+1, str.length());
                i=i+5;
            }else if(str.charAt(i) == ' '){
                str=str.substring(0, i) + "&nbsp;" + str.substring(i+1, str.length());
                i=i+6;
            }
        }
        return str;
    }
    
    /**
     * 내용중에 특수문자 표현을 위해 HTML 특수문자로 변환합니다.
     */
    public static String getConvertBR(String str){
        return str.replace("\n", "<BR>");
    }
    
    /**
     * 파일 Download시 한글 파일 인코딩
     * @param str
     * @return
     */
    public static String getEncoding(String str){
        try{
        //resin UTF-8 로 지정
            //str = java.net.URLEncoder.encode(str, "EUC-KR");
            str = java.net.URLEncoder.encode(str, "UTF-8");
            //str = java.net.URLEncoder.encode(str, "KSC5601");
        }catch(Exception e){
        
        }

        //System.out.println(str);

        for(int i=0; i < str.length(); i++){
            if(str.charAt(i) =='+'){
                str=str.substring(0, i) + "%20" + str.substring(i+1, str.length());
                i=i+3;
            }
        }
        //System.out.println("최종변환 형태: "+str);
        return str;
    }  
    

    /**
     * 파일을 삭제합니다.
     * @param folder 파일이 저장된 폴더
     * @param fileName 삭제할 파일명
     * @return true-삭제 성공, false-삭제 실패
     */ 
    public static boolean deleteFile(String folder, String fileName){
        boolean ret = false;
        
        try{
            if ( fileName != null){ // 기존에 파일이 존재하는 경우 삭제
                File file = new File(folder + "/" + fileName);
                ret = file.delete();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return ret;
    }
    
    /**
     * 주어진 문자셋의 문자코드를 변환합니다.
     * @param ko
     * @return
     */
    public static String flexKo(String ko){
        String corean = null;
        try{
            corean= new String(ko.getBytes("8859_1"), "utf-8");
        }catch(Exception e){
            return corean; 
        }
        return corean;
    }

    /**
     * application이름을 입력받아 절대 경로를 산출합니다.
     * 예) getRealPath(request, "WEB-INF/config")
     * @param request
     * @param dir application 이름
     * @return 절대 경로 리턴
     * @throws IOException
     */
    public static String getRealPath(HttpServletRequest request, String dir) throws IOException {
        // ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        String path = request.getRealPath(dir) + "/";
        System.out.println("Upload path: " + path);
        
        return path;
    }
    
    public static void charsetTest(String s){
       try{
          String [] charset = {"EUC-KR", "KSC5601", "ISO-8859-1", "8859_1", "ASCII", "UTF-8"};
          for(int i=0; i<charset.length; i++)
          {
             for(int j=0; j<charset.length; j++)
             {
                if(i==j) continue;
                System.out.print(charset[i] + " -> " + charset[j] + " : ");
                System.out.println(new String(s.getBytes(charset[i]), charset[j]));
             }
          }
       }
       catch(Exception e){
          e.printStackTrace();
       }
    }    

    /**
     * 주어진 문자셋의 문자코드를 변환합니다.
     * @param ko
     * @return
     */
    public static String ko(String ko){
        String corean = null;
        try{
            //corean= new String(ko.getBytes("iso-8859-1"), "euc-kr");
            //corean= new String(ko.getBytes("iso-8859-1"), "utf-8");
            //corean= new String(ko.getBytes("iso-8859-1"), "iso-8859-1");
            //corean= new String(ko.getBytes("iso-8859-1"), "utf-8");
            //corean= new String(ko.getBytes("iso-8859-1"), "KSC5601");
            corean= new String(ko.getBytes("KSC5601"), "UTF-8");
        }catch(Exception e){
            return corean; 
        }
        return corean;
    }
    
    /**
     * Ajax 한글 변환
     * @param ko
     * @return
     */
    public static String koAjax(String ko){
        String corean = null;
        try{
            // corean= new String(ko.getBytes("ISO-8859-1"), "UTF-8");
            corean= new String(ko.getBytes("KSC5601"), "EUC-KR");
        }catch(Exception e){
            return corean; 
        }
        return corean;
    }
    
    /**
     * 자바스크립트 특수문자, 줄바꿈 문자 변환
     * @param str
     * @return
     */
    public static String toJS(String str) {
        if (str != null){
            return str.replace("\\", "\\\\")
            .replace("\'", "\\\'")
            .replace("\"", "\\\"")
            .replace("\r\n", "\\n")
            .replace("\n", "\\n");
            
        }else{
            return "";
        }
    }      
    
    /**
     * 현재 날짜와 시간을 가져옵니다.
     * @return
     */
    public static String getDateTime(){
        return new Date().toLocaleString().substring(0, 22);
    }  

}




[02] 한글 깨짐의 처리

package www.utility;

import java.util.StringTokenizer;

public class UtilityTest {


    /**
     * 문자열을 바이트 배열 문자열로 변환 
     * @param str
     * @return
     */
     public static String stringToByte(String str){
         String deli=",";  // 구분자 
         String retVal = "";
         try{
             byte[] bstr = str.getBytes("UTF-8");

             for(int i=0; i< bstr.length; i++){
                 retVal = retVal + deli + bstr[i];
             }
         }catch(Exception e){
             
         }
         return retVal;

     }
     
     /**
      * 바이트배열로 되어 있는 문자열을 받아 원래의 문자열로 변환 
      * @param str
      * @return
      */
     public static String byteToString(String str){
         String retVal = "";
         
         try{
             StringTokenizer st = new StringTokenizer(str, ",");
             byte[] _str = new byte[st.countTokens()];
             int i=-1;
             
             while(st.hasMoreTokens()){
                i++;
                 _str[i] = Byte.parseByte(st.nextToken());
             }
             retVal = new String(_str, 0, _str.length, "UTF-8");
         }catch(Exception e){
             
         }

         return retVal;
     } 
     
     
     /**
      * Test
      * @param args
      */
     public static void main(String args[]){
         // --------------------------------------------------------------------------------------------------------------------------------------
         // Http Get 요청 처리 테스트 
         // --------------------------------------------------------------------------------------------------------------------------------------
         String str = "한글 입력 123 abcd !@#$";
         System.out.println("변환에 사용할 원본 문자열: " + str);
         String _str = "";
         _str = stringToByte(str);
         System.out.println("변환: " + _str);
         
         String end = byteToString(_str);
         System.out.println("한글로 변환: " + end);
         
         // -------------------------------------------------------------------------------------------------------------------------------------
     }
}



Posted by ▶파이팅◀

블로그 이미지
Let's start carefully from the beginning
▶파이팅◀

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

글 보관함