// 쿠키생성 : 쿠키에 시간정보를 주지않으면 세션쿠키(브라우저 종료시 모두 종료)
Cookie idCookie = new Cookie("memberId", String.valueOf(loginMember.getId()));
response.addCookie(idCookie);
@GetMapping("/")
public String homeLogin(@CookieValue(name = "memberId", required = false) Long memberId, Model model) {
if(memberId==null) {
return "home";
}
// 로그인
Member loginMember = memberRepository.findById(memberId);
if (loginMember == null) {
return "home";
}
model.addAttribute("member", loginMember);
return "loginHome";
}
private void expireCookie(HttpServletResponse response, String cookieName) {
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
----------- 위에 방식은 보안상의 큰 문제가 있다.--------------
public static final String SESSION_COOKIE_NAME = "mySessionId";
// 동시성 문제가 있을 경우
private Map<String, Object> sessionStroe = new ConcurrentHashMap<>();
/*
세션생성
*/
public void createSession(Object value, HttpServletResponse response)
{
// 세션 아이디 생성하고 값을 세션에 저장
String sessionId = UUID.randomUUID().toString();
sessionStroe.put(sessionId, value);
// 쿠키생성
Cookie mySessionCookie = new Cookie(SESSION_COOKIE_NAME, sessionId);
response.addCookie(mySessionCookie);
}
// 세션조회
public Object getSession(HttpServletRequest request) {
Cookie sessionCookie = findCookie(request, SESSION_COOKIE_NAME);
if (sessionCookie == null) {
return null;
}
return sessionStroe.get(sessionCookie.getValue());
}
public Cookie findCookie(HttpServletRequest request,String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
return Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(cookieName)).findAny().orElse(null);
}
// 세션 만료
public void expire(HttpServletRequest request) {
Cookie sessionCookie = findCookie(request, SESSION_COOKIE_NAME);
if (sessionCookie != null) {
sessionStroe.remove(sessionCookie.getValue());
}
}
@GetMapping("/")
public String homeLoginV2(HttpServletRequest request, Model model) {
// 세션 관리자에 저장된 회원 정보 조회
Member member = (Member)sessionManager.getSession(request);
// 로그인
if (member == null) {
return "home";
}
model.addAttribute("member", member);
return "loginHome";
}