관리 메뉴

샐님은 개발중

3. 로그인 - 서블릿 HTTP 세션 1 본문

스프링 MVC 2편 - 인프런 김영한/섹션 6,7 - 로그인 처리

3. 로그인 - 서블릿 HTTP 세션 1

샐님 2023. 7. 15. 01:49
728x90
반응형

1. HttpSession 

 - 서블릿이 제공하고 JSESSIONID 라는 쿠키 이름을 생성하고 이것은 추정 불가능한 랜덤 값이다.

 

2. HttpSession 적용

1. SessionConst.java 생성  : HttpSession 에 데이터 보관,조회시 같은 이름 중복되므로 상수로 정의.

package hello.login.web;

public class SessionConst {

    public static final String LOGIN_MEMBER ="loginMember";
}

2. LoginController.java 수정 : 클라이언트에서 로그인 요청시 세션사용.

@PostMapping("/login")
public String loginV3(@Validated @ModelAttribute LoginForm form, BindingResult
        bindingResult, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        return "login/loginForm";
    }
    Member loginMember = loginService.login(form.getLoginId(),
            form.getPassword());
    log.info("login? {}", loginMember);
    if (loginMember == null) {
        bindingResult.reject("loginFail", "아이디 또는 비밀번호가 맞지 않습니다.");
        return "login/loginForm";
    }
    //로그인 성공 처리
    //세션이 있으면 있는 세션 반환, 없으면 신규 세션 생성
    // request.getSession(false) 설정하면 세션이 없어도 새로운 세션을 생성하지 않는다.
    // 기본은 true
    
    HttpSession session = request.getSession();
    //세션에 로그인 회원 정보 보관
    session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember);
    return "redirect:/";
}
@PostMapping("/logout")
public String logoutV3(HttpServletRequest request) {
    //세션을 삭제한다.
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    return "redirect:/";
}

3.HomeController.java 수정 :  클라이언트에서 메인 화면 요칭시 세션이 있는지 확인한다.

@GetMapping("/")
public String homeLoginV3(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";
}

 

728x90
반응형