본문 바로가기

개발 에러

3차 프로젝트 개념정리 [2019-11-20~2019-12-20]

 

HashMap 개념

HashMap은 1차원적인 배열을 가지는 List, Set과는 달리 2차원 배열의 형태를 가져 키 값으로 데이터에 접근한다.

<Map>

key와 value를 쌍으로 저장하는 자료구조로 다른 언어에서는 Dictionary 라고 하기도 한다.

 

 

return Type Method and Description
boolean containsKey(Object key)

Returns true if this map contains a mapping for the specified key.

boolean containsValue(Object value)

Returns true if this map maps one or more keys to the specified value.

Set<K>

keySet()

Returns a Set view of the keys contained in this map.

V

 

 

boolean

remove(Object key)

Removes the mapping for the specified key from this map if present.

 

remove(Object key, Object value)

Removes the entry for the specified key only if it is currently mapped to the specified value.

int

size()

Returns the number of key-value mappings in this map.

Collection<V>

values()

Returns a Collection view of the values contained in this map.

V

get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

 

 

ArrayList안에 들어가는 객체를 HashMap으로 지정할 수 있다

ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

(1) 값 가져오기

list.get(인덱스).get( "code" );

(2) 값 넣기

list.get(인덱스).put( "code", 값 );

 

 

프로젝트 진행 중 이 부분에서 에러가 났다

 

HotelBookingDAO.java

	public int getInterval2(String checkin, String checkout){
		
        // 이 부분을 <String,Object>로 줬다
		HashMap<String, String> params = 
				new HashMap<String, String>();
		
		params.put("checkin", checkin);
		params.put("checkout", checkout);

		int interval = 
				sessionTemplate.selectOne("hotelmapper.intervalDay2",params);
		
		return interval;
	}

hotelMapper.xml

<select id="intervalDay2"  parameterType="map" resultType="int">
SELECT trunc(to_date(#{checkout},'yyyy/mm/dd')) 
- trunc(to_date(#{checkin},'yyyy/mm/dd')) FROM dual
</select>

 

그랬더니 #{checkout} 부분에 값이 안들어가는 것이였다. 

 

방안 2개가 있었다 (이 문법은 myBatis3.0에서 해당되는 부분이다)

${val} -> val의 자료형에 상관없이 값이 그대로 치환되어 들어간다

#{val} PrepareSatement 객체가 값을 바인딩하기 위해 val의 자료형에 맞게 쿼테이션이 알아서 적용 된다

 

1. '${checkout}' 으로 바꾸거나

2. #{checkout} 으로 쓸 거면, HashMap<String,String> 으로 바꿔주어야 한다. 그렇게 주지 않아서 발생한 문제였다.

하지만 다른 예제에서는 String,Object로 접근해도 (value값이 전부 String이여도) 가능했었는데 여기선 왜 안됐는지 의문이다. 무튼 고치니깐 됐다

 

 

 


JQuery - 동일 class들에 대해 click 이벤트 처리

document.getElementById(id);

주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 Element 객체를 반환한다.

ID는 문서 내에서 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용하다.

 

반환값 - 주어진 ID와 일치하는 DOM 요소를 나타내는 Element 객체. 문서 내에 주어진 ID가 없으면 null값 반환

 

문서에 없는 요소 getElementById()가 팀색하지 않는다. 요소를 동적으로 생성해서 ID를 부여하더라도, Node.insertBefore()나 비슷한 메서드로 문서 트리에 삽입해야 getElementById()로 접근할 수 있다. 

var element = document.createElement('div');
element.id = 'testqq';
var el = document.getElementById('testqq'); // el이 null!

내가 원했던 로직이 5개의 카드에 대해서 똑같이 saveButton이란 아이디를 준 다음에,

 <li button id="saveButton" 

click되었을 경우 name 값에 따라 카드구분처리를 하려했는데 첫번째에 있는 id값만 click이벤트가 적용되었다.

 

그러다 찾은 답변

dom안에 id는 1개만 존재해야 합니다. 중복되면 뒤의 것들은 모두 무시됩니다. id는 키값입니다. 2개이상 존재할 수 없습니다. id 대신 클래스나 name/type 셀렉터로 객체를 선택해야 합니다.

 

 

[해결한 방법] 동일한 class에 대해 이벤트가 발생한  경우, name값에 따라 처리를 다르게 함

javascript 부분

	$(function() {
		$(".list-inline-item").click(function() {						
			 card = $(this).attr('name');		
			 
			$.get("<%=cp%>/booking-step2_ok.action",{card:card,price:<%=total%>},
					function(args){
					$("#resultDIV").html(args); 
				});
		}); 
		
	});

html 부분

 <div class="ed-pay-card">
    <ul class="list-inline">
    <li button name="visa"  class="list-inline-item"><img src= ...
    <li button  name="master" class="list-inline-item"><img src=...
    <li button name="american" class="list-inline-item" ><img src=...
    <li button  name="maestro" class="list-inline-item"><img src=...
    <li button name="what" class="list-inline-item"><img src=...
    </ul>
</div>

컨트롤러에서 넘긴 모델 값 뷰(jsp)에서 받아서 활용하는 법

 

1. getAttribute로 값 받기

<%
UserInfo userInfo=(UserInfo)request.getAttribute("getUserInfo");
%>

2. el 표현언어 or jstl 이용

 

 

 


getElementById("adult").value 로 이용하자!

 

var adult = document.getElementById("adult");
alert(adult);

결과화면 : [obejct HTMLInputElement] 

-> HTML에서 input요소의 object라는 뜻. 

이 정보는 실제로 쓸 일이 없음!

 

<select id="adult" class="form-control custom-select" value="adult" >
	<option selected style="color:black;">성인</option>
		<option value="1" style="color:black;">1명</option>
		<option value="2" style="color:black;">2명</option>
		<option value="3" style="color:black;">3명</option>
		<option value="4" style="color:black;">4명</option>
		<option value="5" style="color:black;">5명</option>
</select>

 

var adult = document.getElementById("adult").value;
alert(adult);

결과화면: select한 value값이 들어옴

3을 클릭했다면 3이 뜸!

 


2019.11.17 (수) 기록

 

메인 페이지의 호텔 예약 input box에서 이전 기록이 자꾸 자동완성 되어 보였다. 원래 달력만 이쁘게 나와야 하는데..

 

 

 <input type="text" class="form-control" autocomplete="off" placeholder="체크아웃" name="checkout">

 

다음과 같이 autocomplete="off" 라는 속성을 주니 해결되었다

 

 

 

 

*autocomplete에 사용 가능한 옵션 

1. on  - 자동완성 기능 사용 (Default 값)
2. off  - 자동완성 기능 사용 중지

 


체크박스 ajax 쓴 개념 정리 (room-details.jsp)

 

 

 

 

 

페이지 새로고침 되지 않은 채로 체크박스에 따라 비용이 바뀌는 것을 ajax를 이용하여 구현하였다.

 

html부분 - 각 id, value, name 값에 집중!

			    <div class="form-group col-lg-12 mt-4 mb-3">
				 	<h6 class="text-white text-uppercase mb-2">추가 시설</h6>
			 		<div class="form-check">
					  <input class="form-check-input" type="checkbox" 
					  value="30000"  name="야외수영장" id="form-check-input">
					  <label class="form-check-label" for="defaultCheck1">
					    야외수영장 (+30000)
					  </label>
					</div>

					<div class="form-check">
					  <input class="form-check-input" type="checkbox" 
					  	value="13000" name="조식" id="form-check-input">
					  <label class="form-check-label" for="defaultCheck2">
					    조식 (+13000)
					  </label>
					</div>

					<div class="form-check">
					  <input class="form-check-input" type="checkbox" 
					  	value="45000" name="와이너리" id="form-check-input">
					  <label class="form-check-label" for="defaultCheck3">
					     와이너리 (+45000)
					  </label>
					</div>
					<div class="form-check">
					  <input class="form-check-input" type="checkbox" 
					  	value="60000" id="form-check-input" name="스파">
					  <label class="form-check-label" for="defaultCheck5">
					      스파 (+60000)
					  </label>
					</div>

					<div class="form-check">
					  <input class="form-check-input" type="checkbox" 
					  	value="23000" id="form-check-input" name="엑스트라베드">
					  <label class="form-check-label" for="defaultCheck4">
					      엑스트라 베드 (+23000)
					  </label>
					</div>
			    </div>

 

 

 

javascript부분

$(document).ready(function(){
	
	$('input[id="form-check-input"]').change(function() {

        var arrList = new Array(); // 체크박스 가격들 담음
        var optionList = new Array();  // 체크박스 옵션들 담음
        var pricePerNight = ${dto.pricePerNight }; // 1박당 가격
        
    	optionList2.splice(0,optionList2.length); // 배열 요소 제거하여 초기화시킴
            
        $('input[id="form-check-input"]:checked').each(function(i){ // 체크된 요소만 순회하기 위한 반복문  
        	
        		arrList.push($(this).val()); // 해당 value 값이 옴
        		optionList.push($(this).attr("name")); // 해당 name태그의 속성값이 옴
        		// optionList.push(this.name); 이렇게 적어도 됨
        });
        
        if (arrList=="")
        	arrList.push(0);        
        
		$.ajax({
			// 입력창 보내는거니깐 post형태로
			type:"POST",  
			url:"<%=cp%>/room-details_ok.action", 
			data:{arrList:arrList, pricePerNight:pricePerNight},
			success:function(args){
				
				$("#listData").html(args);
                
				 // 초기화된 배열에 다시 담기				 
				for(var i=0;i<optionList.length;i++){
				    optionList2[i]=optionList[i];
				}
			},
			beforeSend:showRequest, 
			error:function(e) {				
				alert(e.responseText); 
			}
		}); 		
	});	
});

 

배열 요소 전체 삭제할 때, delete를 안쓰고 splice메소드를 쓴 이유는

delete optionList2[j];  -> 배열 요소가 완벽히 삭제되는게 아니라 undefined로 들어감 (고로 배열의 length는 동일)

optionList2.splice(0,optionList2.length);  -> 배열 요소가 완벽히 제거됨 (원본손상, length도 줄어들음)

array.splice(start) // 삭제할 배열 요소의 index 번호
array.splice(start, deleteCount) // start로부터 몇개의 번호를 삭제할지
array.splice(start, deleteCount, item1, item2, ...) // 배열에 삭제된 곳으로부터 추가될 요소 (추가될 요소들은 여러개올수있음)

 

 

JQuery checkbox 관련 참조하기 좋은 블로그 

https://openlife.tistory.com/381

https://isstory83.tistory.com/112

 

 


[spring redirect 한글깨짐현상 ] redirect parameter 값이 ?? 로 나오는경우

 

category= URLEncoder.encode(category, "UTF-8");

category= URLEncoder.encode("한글", "UTF-8");

 

다음과 같이 인코딩 해 준 다음 보내야한다.

redirect  파라미터의 값이 URL이기 때문에 URL 안에 URL이 들어간 형태가 되어 제대로 파싱되지 않는다는 문제가 있음

그래서 파라미터로 넘겨야 하는 URL 부분을 URLEncoder로 인코딩하여 

main.do?category=%3A%2F%2 이와 같은형태로 넘겨야 한다

 

원래는 인코딩을 한다면 디코딩을 해주어야 하는데, 이 부분은 다시 디코딩을 해줄 필요가 없다.

URL은 자동으로 웹 서버에서 파싱할때 디코딩을 해주기 때문!

 

'개발 에러' 카테고리의 다른 글

톰캣 에러  (0) 2019.12.09
*2  (0) 2019.12.09
org.apache.ibatis.reflection.ReflectionException  (0) 2019.11.23