03.업/08.개발환경2023. 5. 3. 14:27

한글이 윈도우 2012 의 iis를 웹서버로 하고 톰캣8.0.5를 와스로 설정해서 올라간 웹모듈환경에서 토스결제시에 한글이 깨지는 현상이 발생했다.

 

HttpURLConnection으로 연결하여 InputStreamReader로 읽어올 때 한글 깨짐 방지

1.order***.jsp


...
<meta charset="UTF-8">
...

	<script type="text/javascript">
		/*-- toss payments 결제 모듈 --*/
		const clientKey = '';//운영
		const tossPayments = TossPayments(clientKey);
		
		$(function() {
			/* 취소하기 */
			$("#payCancl").on("click", function(e) {
				e.preventDefault();
				history.back();
			});
			
			/* 결제하기, 토스 결제창 생성 */
			/*  */
			$("#payBtn").on("click", function(e) {
				e.preventDefault();
				
				/* 인자 값 설정 */
				const pay_method = $("#pay_method option:selected").attr("data-name"); // 결제 수단 파라미터
				const amount = ${f_fee };
				const uuid = self.crypto.randomUUID(); // 주문 ID
				const orderName = $("#orderName").text();
				const customerName = $("#customerName").text();
				const customerEmail = $("#customerEmail").text();
				const customerTel = $("#customerTel").text();
				const f_class = $("#f_class").val(); 
				/* const successUrl = encodeURI("https://www.sclass.co.kr/tossPay/success");
				const failUrl = encodeURI("https://www.sclass.co.kr/tossPay/fail"); */
				/* 
					successUrl failUrl : 반드시 작은 따옴표로 설정해야함.에러가나서 결제창이 안뜬다. 					
					successUrl: 'http://localhost:8080/tossPay/success',
					failUrl: 'http://localhost:8080/tossPay/fail',
				*/
				/* 결제 창 생성 */
				tossPayments.requestPayment( pay_method, { 
					amount: amount,
					orderId: uuid,
					orderName: orderName,
					customerName: customerName,	
					successUrl: 'http://localhost:8080/tossPay/success',
					failUrl: 'http://localhost:8080/tossPay/fail',
				})
				.catch(function (error) {
					if (error.code === 'USER_CANCEL') {
						// 결제 고객이 결제창을 닫았을 때 에러 처리
						console.log('USER_CANCEL');
					} else if (error.code === 'INVALID_CARD_COMPANY') {
						// 유효하지 않은 카드 코드에 대한 에러 처리
					}					
				});
			});
		});
		/*--// toss payments 결제 모듈 --*/
	</script>

<meta charset="UTF-8">

 

2.controller

	@RequestMapping(value = "/tossPay/{state}", method = {RequestMethod.GET })
	public ModelAndView tossPayResultController(
									  @PathVariable("state") String state
									, @RequestParam HashMap<String, Object> hashMap
									, HttpSession session
									, ModelAndView mav) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		
		try {
			
			if( "success".equals(state) ) {
				/* 결제 승인 요청 성공 */
				
				/* 결제 승인 요청하기 */
				HashMap<String, Object> payResultMap = paymentService.tossPaymentsConfirm(hashMap);
				....

				switch (String.valueOf( payResultMap.get("method") ) ) {
				case "카드":
                ...
					break;
				default:
					break;
				}
                
				paymentService.insertTbClassPayment(paymentVo);
				result.put("state", "success");
				result.put("msg", "");
				
				mav.setViewName("redirect:/order_result?paymentSeq="+paymentVo.getF_seq());
                ...
		}
		
		return mav;
	}

 

3.service

	public HashMap<String, Object> tossPaymentsConfirm(HashMap<String, Object> hashMap) throws Exception {
		
		String secretKey = ""; // api 시크릿 키
		URL url = new URL("https://api.tosspayments.com/v1/payments/confirm");
		HttpURLConnection con = null;
		
		con = (HttpURLConnection)url.openConnection();
		con.setUseCaches(false);
	    con.setDoOutput(true);
	    con.setDoInput(true);
		String AuthorizationHeader = "Basic " + Base64Utils.encodeToString( (secretKey+":").getBytes() );   
	    con.setRequestProperty("Authorization", AuthorizationHeader);
	    con.setRequestProperty("Content-Type", "application/json");
	    con.setRequestMethod("POST");
	    con.setDoOutput(true);
	    
	    DataOutputStream wr = null;
	    wr =  new DataOutputStream(con.getOutputStream());
	    BufferedReader br = null;
	    InputStreamReader inp = null;
	    
	    HashMap<String, Object> result = null;
	    try {
			ObjectMapper objectMapper = new ObjectMapper();
	        String jsonBody = objectMapper.writeValueAsString(hashMap);
	        
	        wr.write(jsonBody.getBytes());
	        wr.flush();
	        wr.close();
			
	        int responseCode = con.getResponseCode();
	        
	        if(responseCode == 200) { // 정상 호출
	        	inp = new InputStreamReader(con.getInputStream(), "UTF-8");
	            br = new BufferedReader(inp);
	        } else { // 에러 발생
	        	inp = new InputStreamReader(con.getErrorStream(), "UTF-8");
	            br = new BufferedReader(inp);
	        }

	        String inputLine;
	        StringBuffer response = new StringBuffer();
	        while ((inputLine = br.readLine()) != null) {
	            response.append(inputLine);
	        }
	        
	        result = objectMapper.readValue(response.toString(), HashMap.class);
	    } catch (Exception e) {
			throw e;
		} finally {
			if (wr != null) wr.close();
			if (br != null) br.close();
			if (inp != null) inp.close();
			if (con != null) con.disconnect();
		}
	    
	    return result;
	}

4.server.xml

 <Connector ...URIEncoding="UTF-8" .../>

5.web.xml

<filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
		<!--
        <async-supported>true</async-supported>
		-->
	    <init-param>
		    <param-name>ignore</param-name>
		    <param-value>false</param-value>
	    </init-param>
    </filter>
	<filter-mapping>
	  <filter-name>encodingFilter</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>
	...
</filter>

========================================================================

IIS-Tomcat 통합 서버에서 입력 스트림으로 받은 데이터가 한글로 깨져 있다면 인코딩이나 문자셋 설정이 잘못된 경우일 가능성이 높습니다. 데이터를 올바르게 인코딩하려면 다음 단계를 따르십시오.

 

1.웹 애플리케이션 구성에 올바른 인코딩이 설정되어 있는지 확인하십시오. 한국어의 경우 일반적인 인코딩은 UTF-8입니다. web.xml 파일에서 <web-app> 요소 내에 다음 코드 조각을 추가합니다.

<filter>

    <filter-name>encodingFilter</filter-name>

    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>

    <init-param>

        <param-name>encoding</param-name>

        <param-value>UTF-8</param-value>

    </init-param>

    <init-param>

        <param-name>ignore</param-name>

        <param-value>false</param-value>

    </init-param>

</filter>

<filter-mapping>

    <filter-name>encodingFilter</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

 

2.HTML 파일에도 올바른 인코딩이 지정되어 있는지 확인하십시오. HTML 파일의 <head> 태그 내에 다음 줄을 추가합니다.

 

<meta charset="UTF-8">

 

3.IIS 서버에도 올바른 인코딩 설정이 있는지 확인합니다. IIS 관리자에서 웹 애플리케이션으로 이동하고 "구성 편집기"를 엽니다. "system.webServer/globalization"에서 "requestEncoding" "responseEncoding" 특성을 "UTF-8"로 설정합니다. 65001

: 이부분은 설정부분을 못 찾아서 넘어갔다.

 

4.Java 코드를 사용하여 입력 스트림을 읽거나 쓰는 경우 올바른 인코딩을 지정해야 합니다. 예를 들어 입력 스트림을 읽을 때 다음 코드를 사용할 수 있습니다.

 

InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");

BufferedReader br = new BufferedReader(isr);

 

5.여전히 문제가 발생하면 데이터 소스(: 데이터베이스, 파일 또는 외부 서비스)가 올바른 인코딩을 사용하고 있는지 다시 확인하십시오.

 

이러한 변경 사항을 구현한 후 새 설정을 적용하려면 Tomcat IIS 서버를 모두 다시 시작하십시오. 이렇게 하면 IIS-Tomcat 통합 서버에서 받은 한국어 데이터의 인코딩 문제가 해결됩니다.

 

 

IIS 인코딩 설정 관련 UTF-8 한글 깨짐 현상 해결(IIS 설정)

https://server-talk.tistory.com/66

ASP : 코드페이지 > 65001 utf-8로 나온다.

 

'03.업 > 08.개발환경' 카테고리의 다른 글

[펌]탐색기 파일목록 내보내기  (0) 2023.07.12
톰캣설정 및 톰캣콘솔 한글로그 안깨지고 나오게 하기  (0) 2023.05.24
github clone  (0) 2023.01.28
github 정보  (0) 2023.01.09
유닉스기초명령어사용법  (0) 2022.12.27
Posted by 봄날의차