Spring_Cookie와 활용

zooyeong·2023년 6월 4일
0

18주차

목록 보기
4/5
post-thumbnail

📌Cookie란?

웹 서비스는 HTTP 프로토콜을 기반으로 사용자와 통신한다. HTTP 프로토콜은 Stateless 기반인 프로토콜로, 클라이언트와 서버와의 관계를 유지하지 않는 특징이 있다. 이 Stateless 상태를 해결하는 두 가지 방식이 바로 세션(Session)과 쿠키(Cookie)이다.

스프링에서 세션은 지난 시간에 HttpSession을 통해 다뤄보았다.

이번 시간엔 쿠키를 다루기 위해 쿠키 컨트롤러와 @CookieValue 어노테이션을 학습해보았다.


↓ Controller_Cookie 객체 생성(response)

@Controller
public class CookieController {
	
	@RequestMapping("/newCookie")
	public String newCookie(HttpServletResponse response) {
		//쿠키는 response에 담아서 보내기!
		
		try {
			String ck1_str = URLEncoder.encode("넘긴 쿠키", "UTF-8");
			String ck2_str = URLEncoder.encode("서버에서userid쿠키", "UTF-8");
			
			Cookie ck1 = new Cookie("ck1", ck1_str);
			Cookie ck2 = new Cookie("userId", ck2_str);
			
			ck1.setMaxAge(60 * 20); //20분동안 저장
			ck2.setMaxAge(60 * 60 * 24); //1일동안 저장
			
			response.addCookie(ck1);
			response.addCookie(ck2);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "newCookie";
	}
}

↓ 쿠키 생성 결과


↓ Controller_Cookie 객체 생성(request)

@Controller
public class CookieController {
	@RequestMapping("/readCookie")
	public String readCookie(HttpServletRequest request) {
		
		Cookie[] cookies = request.getCookies();
		String value = CookieUtils.findCookie(cookies, "userId");		
		String value2 = CookieUtils.findCookie(request, "userId");
		String value3 = CookieUtils.findCookie(request, "ck1");
		String value4 = CookieUtils.findCookie(cookies, "JSESSIONID");
		
		if(value == null) {
			System.out.println("해당 쿠키가 없는 경우 로직");
		}

		System.out.println("Cookie[]로 찾은 userId 쿠키 값 : " + value);
		System.out.println("request로 찾은 userId 쿠키 값 : " + value2);
		System.out.println("request로 찾은 ck1 쿠키 값 : " + value3);
		System.out.println("Cookie[]로 찾은 JSESSIONID 쿠키 값 : " + value4);

		return "readCookie";
	}
}

↓ CookieUtils 클래스

public class CookieUtils {

	/** request로 쿠키 가져오는 경우 */
	public static String findCookie(HttpServletRequest request,
			String cookieName) {

		Cookie[] cookies = request.getCookies();

		return findCookie(cookies, cookieName);
	}

	/** 쿠키 배열로 받는 경우 */
	public static String findCookie(Cookie[] cookies,
			String cookieName) {

		try {
			for(Cookie ck : cookies) {
				if(ck.getName().equals(cookieName)) {
					String ck_value = URLDecoder.decode(ck.getValue(), "UTF-8");
					return ck_value;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}

↓ 콘솔창 출력결과


↓ Controller_@CookieValue

@Controller
public class CookieController {
	@RequestMapping("/readCookieValue")
	public String readCookieValue(@CookieValue("userId") String userId,
								  @CookieValue("ck1") String ckStr) {
		
		System.out.println(userId);
		System.out.println(ckStr);
		
		return "readCookie";
	}
}

↓ 콘솔창 출력결과

profile
Have a good day ⌯’▾’⌯

0개의 댓글