세션, 쿠키, 인터셉터

황상익·2024년 12월 12일

쿠키, 세션


쿠키는 클라이언트 측에서 확인이 가능, 세션은 서버에서 저장하기 때문에 확인 할 수 없음

참고로 Session은 JSESSIONID 같은 클라이언트마다 고유 ID를 부여하여 요청시 쿠키의 값을 확인하여 구분

SpringSession

HttpSession을 이용해 처리
내부적으로 Servlet Container에게 Session을 획득
- @Autowired를 통해 주입
- 요청 매핑 어노테이션 적용 메서드에 HttpSession 파라미터 추가
- 요청 매핑 어노테이션 적용 메서드에 HttpServletRequest 파라미터를 추가하고, 이를 이용해 HttpSession 구함
- @SessionAttribute, @ModelAttribute로 주입

메서드 주입

@PostMapping
public String form(CommandObject cmdObj, Errors errors, HttpServletRequest req) {
    HttpSession session = req.getSession();
    // session 사용
}

@SessionAttribute, @ModelAttribute로 주입받기

  • Session에 이미 저장된 데이터를 조회할때 적합, 메서드를 호출할 대 Session 요청이 생성
    @SessionAttributes를 컨트롤러에 추가함으로써 세션 단위로 스코프를 지정하도록 명시
@Controller
@SessionAttribute("hello")
public class HelloController {
	@PostMapping("/hello")
    public String submit(Model model, @ModelAttribute("hello") Object obj) {
        model.addAttribute("hello", obj.helloEvery());
		return "test";
	}
}

여기서는 클래스 단위에 넣었지만, 나는 메서드 단위에 넣어서 사용하는 것을 선호

Spring 쿠키 설정

@CookieValue 어노테이션을 이용해서 이용 매핑 어노테이션 적용 메서드에 Cookie 타입 파라미터에 적용하여 사용

@GetMaaping
public String form(
    LoginCommand loginCommand,
    @CookieValue(value = "cookie_name", required = false) Cookie rCookie
) {
    //Cookie 값 얻기, 설정
    String cValue = rCookie.getValue();
    rCookie.setValue("New Value");
    rCookie.setPath("/");
    rCookie.setMaxAge(60 * 60 * 24 * 30);
    rCookie.setSecure(true);
    rCookie.setHttpOnly(true);
    boolean cookieisHttpOnly = rCookie.isHttpOnly();
}

Session은 Request를 받아 서버에 저장, Cookie는 클라이언트로 Response해 줘야 함
HttpServletResponse를 통해 설정 가능

@GetMaaping
public String form( LoginCommand loginCommand, HttpServletResponse res) {
	Cookie myCookie = new Cookie("cookie_name", "value");
    //Cookie 값 얻기, 설정
    //설정 생략
    res.addCookie(myCookie);
}

인터셉터

  1. 인터셉터란?
    HTTPRequest와 컨트롤러가 응답하는 HTTPRespone를 가로채는 역할
    특정 권한이 필요한 페이지 요청 시 권한이 있는지를 확인하거나, 세션이 만료되었는지 확인하는 등 용도

인증 인가는 모든 API에서 항사 먼저 거치도록 구현, 그렇다고 모든 Controller에서 각각 구현하게되면 중복 코드가 많아지고 수정 필요시 작업 번거로움

request가 controller에 도착하기 전에 로직을 수행하도록 Filter를 이용,

Filter VS Interceptor

Filter

  • request가 DispatcherServlet에 도달하기 전에 가로챈다.
  • Web Context에서 실행된다.
    • @ExceptionHandler를 이용한 에러 핸들링을 할 수 없다.
  • 인증, 로깅 검증, 이미지와 데이터 압축, Spring MVC에서 분리하고 싶은 기능

HandlerInterceptor

  • request가 DispatcherServlet를 지나 Controller에 도달하기 전에 가로챈다.
  • Spring Context에서 실행된다.
    • @ExceptionHandler를 이용한 에러 핸들링이 가능하다.
  • 횡단 관심사 처리, 세부적인 인가 검사, SpringContext 또는 모델 조작

HandlerInterceptor

HandlerInterceptor는 앞서 말한 것처럼 Spring Context 내에 존재하며, DispatcherServlet과 Controller 사이에서 request를 가로챌 수 있다.

메서드

HandlerInterceptor (Filter도 비슷)

  • preHandle : Controller 처리 이전에 수행 (true를 리턴하면 체인에 의해 다음 interceptor를 실행)
  • postHandle : Controller 처리 이후 수행
  • afterCompletion : request 처리 완료, 뷰 렌더링 이후 수행
profile
개발자를 향해 가는 중입니다~! 항상 겸손

0개의 댓글