학원/JSP

11/23 49-3 [JSP] Cookie연습2(로그인/아웃처리)

도원결의 2022. 11. 23. 21:13

이 놈 처리의 목적과 메커니즘은 바로 전 포스팅에 설명해 놨으니

여기선 바로 실전으로 가쟈 !!

맨 첫 페이지 앞에서

제일먼저 쿠키값을 얻어와야지 !

 

1. 쿠키값 얻기

CookieExamIndex.jsp

<%
	//요청 헤더에서 쿠키값 읽기
  	Cookie[] cookies = request.getCookies();
	//아이디 저장용
	String username="";		
  	if(cookies != null){		
  		for(Cookie cookie : cookies){
  			String name = cookie.getName();
  			String value = cookie.getValue(); 			
  			//아이디 저장용
  			if("USER_ID".equals(name)) username = value;
  		 }		
      }
  %>

  같은페이지에서 틀 작성 ! 여기서 도 우선 크게 보고  뒤에 작성한 페이지들 끼워 맞추는 것은 천천히 보도록 하자

	<span class="font-weight-bold text-danger mb-2"><%=request.getAttribute("ERROR")==null ?"":request.getAttribute("ERROR") %></span>
    <fieldset class="form-group border p-3">
    	<legend class="w-auto p-3">아이디 저장 예제</legend>
   	    <% if(session.getAttribute("USER_ID") == null){ %> <!-- 로그인 안됐을때 로그아웃 안보이게! -->
    	<form class="form-inline" action="CookieExamLoginProcess.jsp" method="POST">
    	    <label>아이디</label>
    		<input value="<%=request.getParameter("id")==null? username : request.getParameter("id") %>" type="text" name="id" class="form-control mx-2"/>  			
    			<label>비밀번호</label>
    			<input value="<%=request.getParameter("pwd")==null? "" : request.getParameter("pwd") %>" type="password" name="pwd" class="form-control mx-2" />
    			<div class="custom-control custom-checkbox">
					<input type="checkbox" class="custom-control-input" name="id-save" value="Y" id="id-save" <% if(username.length()!=0){%>checked<%} %> >
					<label class="custom-control-label" for="id-save" >아이디 저장</label>
				</div>
    		   <input type="submit" class="btn btn-danger mx-2" value="로그인"/>
    	</form>
    <%} else { %>
    		<a href="CookieExamLogout.jsp" class="btn btn-info">로그아웃</a> 	
    <%} %>	
    	</fieldset>

 

2. 로그인 처리를 짜는 페이지 작성(자동으로 바로이동시키는 페이지)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- CookieExamLoginProcess.jsp -->
<%@ include  file="/common/Validate.jsp"%>  <!--유효성 체크-->
<%
	//사용자 입력값 받기
	String id = request.getParameter("id");
	if(!isValidate(out, id, "아이디를 입력하세요")) return;
	String pwd = request.getParameter("pwd");
	if(!isValidate(out, pwd, "비밀번호를 입력하세요")) return;
	String idSave = request.getParameter("id-save");  <!-- 아이디를 계속 저장해 놓을건지 체크박스-->
	//아이디 KIM / 비밀번호 1234면 회원
	if("KIM".equals(id.trim()) && "1234".equals(pwd.trim())){//회원
		//1.로그인처리-세션영역에 속성 저장 주로 식별자인 아이디만! (예습이라생각)
		session.setAttribute("USER_ID", id.trim());
		session.setAttribute("USER_PWD", pwd.trim());
		
		//아이디저장 체크 여부 판단
		if(idSave != null){ //체크 한 경우-아이디를 쿠키에 저장
			Cookie cookie = new Cookie("USER_ID",id.trim());
			cookie.setPath(request.getContextPath());
			response.addCookie(cookie);
		}
		else{//체크 안 한 경우-저장된 쿠키 삭제
			Cookie cookie = new Cookie("USER_ID","");
			cookie.setPath(request.getContextPath());
			cookie.setMaxAge(-1);
			response.addCookie(cookie);
		}
        
        
		//2.로그인 처리후 CookieExamIndex.jsp로 이동		
		response.sendRedirect("CookieExamIndex.jsp");
	}
	else{//아이디 비번 불일치
		//리퀘스트 영역에 필요한 데이터 저장
		request.setAttribute("ERROR", "아이디와 비번 불일치");
		//포워드로 이동 이거! ERROR메시지는 로그인 페이지에서 띄워야하니까 포워드방식으로 보내야 객체가 살아있다! 
		request.getRequestDispatcher("CookieExamIndex.jsp").forward(request, response);
	}
%>

 

 

3. 로그아웃처리 (이거도 바로 자동이동페이지)

CookieExamLogout.jsp 로그인은 세션영역에 저장하는법이라면 로그아웃은 세션영역을 삭제하는 것 !

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- CookieExamLogout.jsp  -->
<%
	//방법1.아이디와 비밀번호를 각각 지우거나
/*  session.removeAttribute("USER_ID");
	session.removeAttribute("USER_PWD");   */
	//방법2. 걍 싹 비우거나
	session.invalidate();

	//로그아웃 처리 후 이동, 여기선 돌아갈페이지에서 뭐 할 거 없으니까 리다이렉트로 이동해버려
	response.sendRedirect("CookieExamIndex.jsp");
%>

 

로그인 된 화면
로그아웃 된 화면 (로그인할 때 저장 해놈 )