본문 바로가기
Spring

Session을 받는 여러방법 중 가장 표준적인 방법

by windy7271 2024. 2. 2.
728x90
반응형

 

로그인에 성공을 했을시. 그 로그인 한 사람의 세션정보를 얻는 방법이 대표적으로 3가지가 있습니다.

 

3가지 모두 알아보고 가장 많이 쓰는 것을 알아보겠습니다.

 

1. Session attribute를 통한 접근

 public String userInfoTeset(HttpServletRequest request) {
        String email1 = request.getSession().getAttribute("email").toString();
}

 

장점 : 직관적이며 간결합니다

단점 : 세션에 직접적으로 속성을 저장해야하므로 유지보수 측에서 관리가 어렵고,세션일 없는경우 Nullpointexeptcion 경우도 있습니다

 

2.  session에서 Authentication 객체를 접근

SecurityContext springContext = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
String email2 = springContext.getAuthentication().getName();

 

장점 : Security가 제공해 줍니다.

단점: 1번보다는 안전하지만, 예외처리가 필요합니다.

 

 

3. SecurityContextHolder에서 Authentication객체를 접근 (제일 많이씁니다)

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();

 

Security 가 제공하는 표준적이고 안전한 방법이고, 대부분 상황에서 사용가능합니다.

단점 : 이해가 어렵습니다.

 

결론은 이해하시고 3번 쓰시면 됩니다.

 

반응형

댓글