본문 바로가기
개발 공부 Today I Learned

[국비 70일차 TIL] 쿠키 & 세션, 게시판 ip 검색

by 개발자신입 2024. 3. 5.
반응형

쿠키 & 세션

가장 큰 차이점은 사용자의 정보가 어디에 저장되느냐의 차이임. 캐시와는 다름.

 

쿠키

  • 클리이언트, 브라우저에 저장 (내 컴퓨터), 서버의 자원 활용 안 함.
  • 이름, 값, 유효시간, 도메인, 경로 등을 저장함.
  • 클라이언트에 총 300개의 쿠키 저장 가능.
  • 도메인당 20개만 가질 수 있음.
  • 크기는 4096byte(4KB)까지만 저장 가능.

세션

서버에 저장, 서버의 자원 활용함. 

  세션 쿠키
사용 예시 로그인 쇼핑정보, 장바구니, 자동 로그인
저장 위치 서버 브라우저
속도 느림 빠름
보안 높음 낮음 (위조, 변조 가능)

login.jsp

						<div class="mb-3 row">
							<div class="col-sm-12 text-start">
								<input type="checkbox" class="saveID" id="saveID">
								<label for="saveID">아이디 저장</label>
							</div>
						</div>

 

로그인 버튼 타입 기존의 submit -> button으로 변경 
form태그에 id 추가 :  id="loginForm"

					<form action="./login" method="post">
						<h2 class="text-center text-uppercase text-primary mb-4">LOGIN</h2>

						<div class="form-group">
							<!-- <label id="id"></label> -->
							<input type="text" id="id" name="id" class="form-control" placeholder="아이디">
						</div>

						<div class="form-group">
							<input type="password" id="pw" name="pw" class="form-control" placeholder="비밀번호">
						</div>

						<div class="mb-3 row">
							<div class="col-sm-12 text-start">
								<input type="checkbox" class="saveID" id="saveID"> <label for="saveID">아이디 저장</label>
							</div>
						</div>
						<div class="mb-3 row">
							<div class="col-md-6 offset-md-3">
								<div class="text-center">
									<button type="button" class="btn btn-primary check"  style="width: 100%;">로그인</button>
								</div>
							</div>
							<div class="text-center" style="margin-top: 50px;">
								<a href="./join">아직 회원이 아니라면? 가입하기</a>
							</div>
						</div>
					</form>

 

check function 만들기

<script type="text/javascript">
	$(function() {
		// alert("구동하려면 jQuery 필요");
		// ID, PW 검사
		$('.check').click(function() {
			let id = $('#id').val();
			let pw = $('#pw').val();
			if (id == '' || id.length < 3) {
				alert("올바른 아이디를 입력하세요.");
				$('#id').focus();
				return false;
			}
			if (pw == '' || pw.length < 3) {
				alert("비번 문제");
				$('#pw').focus();
				return false;
			}
			// 쿠키에 id 저장하기
			// if문으로 사용자가 아이디 저장 체크했는지 확인하기 (체크한 사람만 저장해야 함.)
			if($('#saveID').is(':checked')){
				// alert(id+" 아이디 저장 체크함.");
				
				// id불러와서 저장하기
				setCookie("userInputId", id, 60); // 쿠키 저장하는 함수
			}
			$('#loginForm').submit();
		});
	});
</script>

 

쿠키 저장하는 함수

<script type="text/javascript">
	$(function() {
		// 쿠키 가져오기 = getCookie (아래에서 쿠키 가져오기 작성 후 여기로 왔음)
		let userInputId = getCookie("userInputId");
		let setCookieYN = getCookie('setCookieYN');
		
		if(setCookieYN == 'Y') {
			$('#id').val(userInputId);
			$('#saveID').prop("checked", true);
		} 
		

		// alert("구동하려면 jQuery 필요");
		// ID, PW 검사
		$('.check').click(function() {
			let id = $('#id').val();
			let pw = $('#pw').val();
			if (id == '' || id.length < 3) {
				Swal.fire("", "올바른 아이디를 입력하세요.","warning");
				//alert("올바른 아이디를 입력하세요.");
				$('#id').focus();
				return false;
			}
			if (pw == '' || pw.length < 1) {
				Swal.fire("", "올바른 비밀번호를 입력하세요.","warning");
				//alert("비번 문제");
				$('#pw').focus();
				return false;
			}
			// 쿠키에 id 저장하기
			// if문으로 사용자가 아이디 저장 체크했는지 확인하기 (체크한 사람만 저장해야 함.)
			if ($('#saveID').is(':checked')) {
				// alert(id+" 아이디 저장 체크함.");

				// id불러와서 저장하기
				setCookie('setCookieYN', 'Y', 60)// 아이디 저장을 클릭했는지 저장
				setCookie("userInputId", id, 60); // 쿠키 저장하는 함수
			} else {
				// 사용자가 id 저장을 누르지 않음 = 저장 안 함
				delCookie('userInputId');
				delCookie('setCookieYN');
			}
			$('#loginForm').submit();
		});
	});

	//쿠키 저장하는 함수 (쿠키이름, 값, 기한)
	function setCookie(cookieName, value, exdays) {
		//오늘 날짜 뽑기
		let date = new Date();
		//alert("오늘날짜:"+date.getDate() + "/60더한 날짜 : " +date.getDate()+exdays);
		//alert(date.setDate(date.getDate()));
		//alert(date.setDate(date.getDate() + exdays));
		date.setDate(date.getDate()+exdays);
		let value2 = escape(value) + "; expires =" + date.toGMTString();
		// escape() 아스키 문자에 해당하지 않는 문자들은 모두 유니코드 형식으로 변환됨
		document.cookie = cookieName + "=" + value2;
	}

	//쿠키값 가져오기(가져올 쿠키 이름)
	function getCookie(cookieName) {
		let x, y;
		let val = document.cookie.split(';');
		// alert("가져온 쿠키값 : " +val);
		for(let i = 0; i < val.length; i++){
    		x = val[i].substr(0, val[i].indexOf('='));//저장한 쿠키이름
    		y = val[i].substr(val[i].indexOf('=') + 1);//쿠키 값
    		x = x.replace(/^\s+|\s+$/g, ''); // 앞과 뒤의 공백 제거하기
    		if(x == cookieName){
    			return y;
    		}
		}
	}
	
	// 삭제하기 (삭제할 쿠키 이름)
	function delCookie(cookieName){
		// let date = new Date();
		// date.setDate(date.getDate() -1); // 하루 지나면 삭제
		// document.cookie = cookieName + "=; expires=" + date.toGMTSTring();
		document.cookie = cookieName + "=; max-age=0"; //꼭!
	}
	
	
</script>

게시글 리스트에 ip 추가하기

admin-mapper.xml

boardList의 sql문 수정 : 

		 if(date_format(current_timestamp(),'%Y-%m-%d') = 
         date_format(b.board_date,'%Y-%m-%d'),date_format(b.board_date,'%h:%i'),
         date_format(b.board_date,'%m-%d')) AS board_date,

 

boardList의 sql 전체 코드

	<select id="boardList" parameterType="searchDTO" resultType="boardDTO">
		SELECT b.board_no, b.board_title, m.mname, m.mid, 
		if(date_format(current_timestamp(),'%Y-%m-%d') = 
        date_format(b.board_date,'%Y-%m-%d'),date_format(b.board_date,'%h:%i'),
        date_format(b.board_date,'%m-%d')) AS board_date, b.board_ip, b.board_del 
		FROM board b JOIN member m ON b.mno=m.mno
		<where>
			<if test="searchTitle == 1">
				b.board_title LIKE CONCAT('%',#{search},'%')
			</if>
			<if test="searchTitle == 2">
				b.board_content LIKE CONCAT('%', #{search}, '%')
			</if>	
			<if test="searchTitle == 3"> <!-- 작성자 -->
				m.mname LIKE CONCAT('%', #{search}, '%')
			</if>	
		</where>
		ORDER BY b.board_no DESC
		LIMIT #{pageNo}, #{recordCountPerPage};
	</select>

 

컬럼에 IP 추가

						<tr class="row">
							<th class="col-1 text-center">번호</th>
							<th class="col-4 text-center">제목</th>
							<th class="col-1 text-center">글쓴이</th>
							<th class="col-2 text-center">날짜</th>
							<th class="col-2 text-center">IP</th>
							<th class="col-1 text-center">읽음</th>
							<th class="col-1 text-center">보기</th>
						</tr>
					</thead>
					<tbody>
						<c:forEach items="${list }" var="row">
							<tr class="row<c:if test="${row.board_del eq 0}"> bg-dark</c:if>">
								<td class="col-1 text-center">${row.board_no }</td>
								<td class="col-4">${row.board_title }</td>
								<td class="col-1"><a href="./board?searchTitle=3&search=${row.mname }">${row.mname }</a></td>
								<td class="col-2 text-center">${row.board_date }</td>
								<td class="col-2 text-center">${row.board_ip }</td>
								<td class="col-1 text-center">${row.board_count }</td>
								<td class="col-1 text-center">
// 옵션에도 추가
<option value="4" <c:if test="${searchTitle eq 4 }">selected="selected"</c:if>>IP 검색</option>

// ip에 a태그
<a href="./board?searchTitle=4&search=${row.board_ip}">${row.board_ip }</a>

admin-mapper.xml

boardList, totalRecordCount에 4번 추가하기

			<if test="searchTitle == 4"> 
				b.board_ip = #{search}
			</if>

board.jsp

				
	$(function(){
		 $('#perPage').change(function () {
	            location.href = "./board?pageNo=${pageNo}&perPage=${perPage}&searchTitle=${searchTitle}&search=${search}";
		});

글 제목 클릭하면 새로운 페이지로 열기 target

<target="_blank"> // 새로운 창 열기

<a href="./detail?no=${row.board_no }" target="_blank">${row.board_title }</a>

AdminContorller

		@GetMapping("/detail")
	public String detail() {
		return "/admin/detail";
	}

								
	@GetMapping("/detail")
	public String detail(@RequestParam("no") String no, Model model) {
		// 데이터베이스에서 받아오기
		BoardDTO detail = adminService.detail(no);
		
		// Model에 붙여주기
		model.addAttribute("detail", detail);
		return "/admin/detail";
	}

-> detail 만들어주기 (서비스, 서비스Impl, DAO)

AdminService

BoardDTO detail(String no);

 

AdminServiceImpl

빨간줄 오류나는거 add해주기

	@Override
	public BoardDTO detail(String no) {
		return adminDAO.detail(no);
	}

admin-mapper.xml

   <select id="detail" parameterType="Integer" resultType="boardDTO">
      SELECT board_no, board_title, board_content, mname, mid,
      board_date, board_del, board_ip 
      FROM board b JOIN member m ON b.mno =m.mno 
      WHERE board_no=#{no} AND board_del = '1'
   </select>

detail.jsp

 <a href="./detail?no=${row.board_no }" target="_blank">${row.board_title }</a>

// a태그 대신에 onclick로 변경

<td class="col-4" onclick="detail(${row.board_no})">
								${row.board_title }
								</td>

 

	function detail(no){
		// window.open('주소','타이틀', '크기or설정');
		window.open('./detail?no='+no,'게시글 상세보기', 'width=800px, height=800px, scrollbars=auto');
	}
반응형

댓글