다연이네

[days07] 쿠키를 사용해 로그인 처리(상태관리)(회원/비회원/관리자) 본문

JSP

[days07] 쿠키를 사용해 로그인 처리(상태관리)(회원/비회원/관리자)

 다연  2021. 1. 4. 18:46
반응형

쿠키

1. 상태관리 - 클라이언트
2. 텍스트 파일
3. URL요청 + 쿠키값 -> 서버 전송
4. 서버 쿠키 : JSP, Servlet
      js : cookie.js 했듯이
      src : com .util 패키지 안에 Cookies.java

 

 

 [ 쿠키를 사용해서 로그인 처리(상태 관리) ]
  1. ex02_default.jsp
   메인 페이지
   로그인 + 로그아웃
   id/passwd

 

  2. ex02_logon.jsp 
   입력받은 id/password 인증 처리 
   - 로그인 성공 : auth 쿠키이름으로 id 저장 
   - 로그인 실패 : ex02_default.jsp?error (메인 페이지) 이동

기본 화면

로그인 실패시


  3. ex02_board.jsp 게시판 관련 페이지
   - 로그인 하지 않은 사용자라면 게시글 목록 보기 (권한부여)
   - 로그인 인증 + 일반 사용자 : 글쓰기 (권한부여)
   + 관리자   : 글쓰기, 수정, 삭제 (권한부여)

관리자 로그인


일반 회원 로그인

관리자로 로그인 후 게시판 클릭
일반 회원으로 로그인 후 게시판 클릭


  4. ex02_logout.jsp
   - 로그아웃 버튼을 클릭할 때 auth 쿠키 삭제 
   - ex02_default .jsp 메인 페이지로 이동

 

 

 

Cookies.java

package com.util;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


//서버에서 쿠키를 다루는 클래스 라이브러리
public class Cookies {

	public Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
	
	public Cookies(HttpServletRequest request) {
		//쿠키값을 얻어와서 Map 안에 저장하는 일을 생성자에서 하겠다.
		Cookie [] cookies = request.getCookies();
		if(cookies!=null) {
			for (int i = 0; i < cookies.length; i++) {
				//String key = cookies[i].getName();
				//Cookie value = cookies[i];
				//this.cookieMap.put(key, value); 
				
				//변수선언 없이 바로 집어 넣는 것이 성능상 좋은 코딩
				this.cookieMap.put(cookies[i].getName(), cookies[i]); 
			}//for
		}//if
	}//constructor
	
	public Cookie getCookie(String cname) {
		//맵 안의 쿠키 이름에 해당하는 쿠키 객체 자체 리턴
		return this.cookieMap.get(cname); 
	}
	
	//쿠키맵 안에 쿠키 존재 여부 반환 메소드
	//존재하면 true, 존재하지 않으면 false
	public boolean exists(String cname) {
		return this.cookieMap.get(cname) != null;
	}
	
	//쿠키 객체를 생성해서 반환하는 메소드
	public static Cookie createCookie(String cname, String cvalue
			, String domain, String path, int expiry) throws UnsupportedEncodingException {
		Cookie cookie = new Cookie(cname, URLEncoder.encode(cvalue,"UTF-8"));
		cookie.setDomain(domain);
		cookie.setPath(path);
		cookie.setMaxAge(expiry);
		return cookie;
	}
	
	//도메인 없이 생성
	public static Cookie createCookie(String cname, String cvalue
			, String path, int expiry) throws UnsupportedEncodingException {
		Cookie cookie = new Cookie(cname, URLEncoder.encode(cvalue,"UTF-8"));
		cookie.setPath(path);
		cookie.setMaxAge(expiry);
		return cookie;
	}
	
	//cname과 cvalue만
	public static Cookie createCookie(String cname, String cvalue) throws UnsupportedEncodingException {
		Cookie cookie = new Cookie(cname, URLEncoder.encode(cvalue,"UTF-8"));
		return cookie;
	}
	
	public String getValue(String cname) throws UnsupportedEncodingException {
		Cookie cookie = this.cookieMap.get(cname);
		if(cookie==null) return null;
		return URLDecoder.decode(cookie.getValue(), "UTF-8");
	}
	
}//class

 

ex02_default.jsp 

<%@page import="com.util.Cookies"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@include file="auth.jspf" %>
<%
  //auth 쿠키이름으로 id 저장 유무에 따라 인증 여부 확인
  /* 
  String auth = null;
  String cname= "auth";
  Cookies cookies = new Cookies(request);
  if(cookies.exists(cname)){
	  auth = cookies.getValue(cname);
  }
   */
   
   //위의 코딩 들을 auth.jspf  파일로 빼고 -> include 지시자를 사용해 수정
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
 div{
   border: 1px solid gray;
   width: 300px;
   height: 100px;
   padding: 20px;
 }
</style>
<script>
   $(document).ready(function (){     
	   $("#logon span").fadeOut(5000);
   });
</script>
</head>
<body>
 <h3>default(main) page</h3>
 
 
 <%
   if(auth==null){
%>

 <div id="logon">
   <form action="ex02_logon.jsp">
     아이디: <input type="text" name="id" value="admin" /><br>
     비밀번호: <input type="password" name="passwd" value="1234"  /><br>
     <input type="submit" value="로그인" />
     <input type="button" value="회원가입" />
     <br>
     <%
     //?error 달려있다면
    String error = request.getParameter("error");
    if(error != null){
    %>
    <span style="color: red">로그인 실패했습니다.</span>
    <%
    }
     %>
   </form>
 </div>
<%	   
   }else{
%>
 <div id="logout">
 [<%=auth %>]님 환영합니다.<br>
 <a href="ex02_logout.jsp">로그아웃</a>
 </div>
<%
   }
 %>
 
 <!-- 인증, 권한 따라 사용할 메뉴 처리 -->
<!--  게시판과 공지사항은 인증/권한 없이 사용 가능 -->
 <a href="ex02_board.jsp">게시판</a><br>
 <a href="ex02_notice.jsp">공지사항</a><br>
 
 <%
   if(auth!=null){ //로그인 되어졌음 (인증O)
%>
   <a href="#">일정관리</a><br>
   <a href="#">자료실</a><br>
<%
     if(auth.equals("관리자")){
    %>
       <a href="#">사원관리-(관리자 권한)</a><br>
       <a href="#">급여관리-(관리자 권한)</a><br>
    <%
     }
   }
 %>
</body>
</html>

 

 

ex02_logon.jsp

<%@page import="com.util.Cookies"%>
<%@page import="java.util.HashMap"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

   //member 컬렉션
   HashMap<String, String> member = new HashMap<>();
   member.put("admin","1234"); //관리자 권한
   member.put("hong","1234");   //일반 권한
   member.put("park","1234");    //일반 권한
   
   //위가 db라고 가정 (시간관계상)
   String id = request.getParameter("id");
   String passwd = request.getParameter("passwd"); 
   
   if(id.equals("admin")&&passwd.equals("1234")){
	   Cookie cookie = Cookies.createCookie("auth", "관리자", "/", -1);
	   response.addCookie(cookie); 
	   response.sendRedirect("ex02_default.jsp");
   }else if(id.equals("hong")&&passwd.equals("1234")){
	   Cookie cookie = Cookies.createCookie("auth", id, "/", -1);
	   response.addCookie(cookie); 
	   response.sendRedirect("ex02_default.jsp");
   }else if(id.equals("park")&&passwd.equals("1234")){
	   Cookie cookie = Cookies.createCookie("auth", id, "/", -1);
	   response.addCookie(cookie); 
	   response.sendRedirect("ex02_default.jsp");
   }else{
	   response.sendRedirect("ex02_default.jsp?error");
   }
   
%>

 

ex02_logout.jsp

<%@page import="com.util.Cookies"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="auth.jspf" %>
<%
/* 
 String auth = null;
 String cname= "auth";
 Cookies cookies = new Cookies(request);
 if(cookies.exists(cname)){
   auth = cookies.getValue(cname);
 }
  */
 //auth 쿠키 제거
 int expiry = 0;
 Cookie cookie = cookies.createCookie(cname, "", "/", expiry);
  //cookie.setMaxAge(0);
  response.addCookie(cookie);
  
  //메인 페이지로 이동
  //response.sendRedirect("ex02_default.jsp"); 왜 이거 안쓰냐면
  //중간에 경고창을 띄우고 이동하려고 script에서 작성
%>
<script>
  alert("[<%=auth%>]님 로그아웃 되었습니다.");
  location.href="ex02_default.jsp";
</script>

 

ex02_board.jsp

<%@page import="com.util.Cookies"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="auth.jspf" %>
<%
/* 
  //auth 쿠키이름으로 id 저장 유무에 따라 인증 여부 확인
  String auth = null;
  String cname= "auth";
  Cookies cookies = new Cookies(request);
  if(cookies.exists(cname)){
	  auth = cookies.getValue(cname);
  }
   */
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
   });
</script>
</head>
<body>
<a href="ex02_default.jsp">Home</a>
<br />
<a href="ex02_list.jsp">글목록</a>
<!-- 
글쓰기 - 일반 권한, 관리자 권한
글수정, 삭제 - 관리자 권한
 -->
 <%
    if(auth != null){
 %>
   <a href="#">글쓰기</a>
   <%
     if(auth.equals("관리자")){
    	 %>
    	 <a href="#">글수정</a>
    	 <a href="#">글삭제</a>
    	 <%
     }
    }
 %>
</body>
</html>

 

 

겹치는 코딩은 auth.jspf 로 따로 빼두었다. (ex02_default.jsp / ex02_logout.jsp / ex02_board.jsp)

이럴 경우 지시자를 사용해 include 시킨다.

<%@page import="com.util.Cookies"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
  //auth.jspf
  String auth = null;
  String cname= "auth"; 
  Cookies cookies = new Cookies(request);
  if(cookies.exists(cname)){
	  auth = cookies.getValue(cname);
  }
%>

 

반응형

'JSP' 카테고리의 다른 글

[days07] 세션(Session)  (0) 2021.01.04
[days07] 커넥션 풀 (Connection Pool)  (0) 2021.01.04
[days06] 쿠키 (쿠키수정 추가 필요)  (0) 2021.01.01
[days05] 게시판 만들기  (0) 2020.12.29
[days05] 자바 빈즈(Java Beans)  (0) 2020.12.29
Comments