스프링/Spring

[SpringBoot] 서블릿의 HttpSession을 사용해 세션 구현하기

킵고잉 개발자 2021. 10. 26. 13:14

 

HttpSession 소개

서블릿을 통해 HttpSession을 생성하면 다음과 같은 쿠키를 생성합니다.

쿠키 이름이 JSESSIONID이고, 값은 추정 불가능한 랜덤 값입니다.

Cookie: JSESSIONID=5B78E23B513F50164D6FDD8C97B0AD05

 

HttpSession 사용

먼저 세션의 키로 사용될 문자열을 정의합니다.

public class SessionConst {
    public static final String LOGIN_MEMBER = "loginMember";
}

 

@PostMapping("/login")
public String login(@Valid @ModelAttribute LoginForm form, BindingResult bindingResult,
                          HttpServletRequest request){

        if (bindingResult.hasErrors()){
            return "login/loginForm";
        }

        Member loginMember = loginService.login(form.getLoginId(), form.getPassword());

        if (loginMember == null){
            bindingResult.reject("loginFali", "아이디 또는 비번이 맞지 않아~~");
            return "login/loginForm";
        }

        // 로그인 성공 처리
        // 세션이 있으면 있는 세션 반환, 없으면 신규 세션 생성
        HttpSession session = request.getSession();
        // 세션에 로그인 회원 정보 보관
        session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember);
        return "redirect:/";
}

 

세션 생성과 조회

세션을 생성하려면 request.getSession(true) request.getSession(true)를 사용하면 됩니다.

public HttpSession getSession(boolean create);

 

  • request.getSession(true)
    • 세션이 있으면 기존 세션을 반환합니다.
    • 세션이 없으면 새로운 세션을 생성해서 반환합니다.
  • request.getSession(false)
    • 세션이 있으면 기존 세션을 반환합니다.
    • 세션이 없으면 새로운 세션을 생성하지 않는다. null을 반환합니다.
  • request.getSession() : 신규 세션을 생성하는 request.getSession(true)와 동일합니다.

 

세션에 로그인 회원 정보 보관

session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember);

세션에 데이터를 보관하는 방법은 request.setAttribute(..)와 비슷합니다. 하나의 세션에 여러 값을 저장할 수 있습니다.

 

세션 만료하기 - 로그아웃

@PostMapping("/logout")
public String logout(HttpServletRequest request){
        // 세션을 삭제한다.
        HttpSession session = request.getSession(false);
        if (session != null){
            session.invalidate();
        }
        return "redirect:/";
}

 

HttpSession의 invalidate()를 사용하면 현재 가지고 있는 세션을 제거할 수 있습니다.

 

세션 조회하기

@GetMapping("/")
public String homeLogin(HttpServletRequest request, Model model) {

        // 세션이 없으면 home
        HttpSession session = request.getSession(false);
        if (session == null) {
            return "home";
        }

        Member loginMember = (Member) session.getAttribute(SessionConst.LOGIN_MEMBER);

        // 세션에 회원 데이터가 없으면 home
        if (loginMember == null) {
            return "home";
        }

        // 세션에 회원 데이터가 있으면 로그인한 유저를 위한 홈 화면으로 이동
        model.addAttribute("member", loginMember);
        return "loginHome";
}
  • request.getSession(false) : request.getSession()를 사용하면 기본 값이 create: true이므로, 로그인하지 않을 사용자도 의미 없는 세션이 만들어집니다. 따라서 세션을 찾아서 사용하는 시점에는 create: false 옵션을 사용해서 세션을 생성하지 않아야 합니다.
  • session.getAttribute(SessionConst.LOGIN_MEMBER) : 로그인 시점에 세션에 보관한 회원 객체를 찾습니다.

크롬으로 테스트한 경우 개발자 도구 > Application > Cookies에서 세션 값을 확인할 수 있습니다.