교재 내용은 매우 레거시한 내용

 

이 챕터에서 살펴봐야 할 내용인 

HttpSession

HandlerInterceptor

쿠키

 

이 세가지에 대해 간략하게 설명

 

 

 

컨트롤러에서 HttpSession 사용하기

 

public class test (HttpSession session){

	...
}

public class test (HttpServletRequest request) {
	HttpSession session = reqeust.getSession();
    ..
}

 

파라메터로 HttpSession을 받는 방식, HttpServletRequest.getSession() 으로 세션 가져오는 방식

두 개 모두 사용 가능

 

HttpSession 객체에서는 Session Attribute 접근 가능

 

session.getAttribute("authInfo", authInfo);

와 같이 사용

 

 

인터셉터 사용하기

 

HandlerInterceptor 인터페이스를 상속받는 Interceptor 커스텀 클래스를 구현해서

인터셉터 사용 가능

 

preHandle :: 컨트롤러 객체 실행 이전

postHandle :: 컨트롤러 객체 실행 이후, 뷰 실행 전

afterCompletion :: 뷰 실행 이후

 

각각의 시점에 맞게 동작에 관해 인터셉터 구현 가능

 

 

 

 

** 이거 구현하는거보다 

Aop

Spring security FilterChain

Servlet Filter 

사용

 

대부분의 인터셉터의 경우 인증 상태 검사, 권한 검사, 로깅, XSS 대응 등에 사용하는데

그냥 Security Filter 에서 구현하는게 나음

 

 

컨트롤러에서 쿠키 사용

 

@CookieValue

 

쿠키 생성

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/hello")
public class HelloController {
    @PostMapping
    public String submit(HttpServletResponse response) {

      //쿠키  객체 생성, "cookieName"이라는 이름으로 쿠키를 생성하고, 그 값은 "cookieValue"로 설정
      Cookie rememberCookie = new Cookie("cookieName", "cookieVlaue");

      // 쿠키 경로 설정, "/"는 모든 경로에서 사용하겠다는 뜻
      rememberCookie.setPath("/");

      // 쿠키를 유지할 시간 설정(단위 : 초)
      rememberCookie.setMaxAge(60*60*24*30); // 30일 동안 쿠키 유지.

      response.addCookie(rememberCookie);

      return "hello";

    }

}

 

 

쿠키 전달

import org.springframework.web.bind.annotation.CookieValue;
import javax.servlet.http.Cookie;

@Controller
@RequestMapping("/hello")
public class HelloController {
    @GetMapping
    public String form(@CookieValue(value = "cookieName", required = false) Cookie coookie) {

        //이름이 "cookieName"인 쿠기가 존재한다면?
        if(cookie != null) {

              //cookieValue 변수에 쿠키 값을 저장한다.
             String cookieValue = cookie.getValue();         
        }

        return "hello";
    }
}

+ Recent posts