본문으로 바로가기

[JSP] Spring Cookie & Session

category Dev/JSP 2018. 10. 10. 10:52


Cookie

Cookie란?

클라이언트 단에 저장되는 작은 정보의 단위


설정 과정

1. Web Client가 WAS에게 요청

2. WAS가 쿠키를 생성하여 Web Client에게 응답

3. 저장된 쿠키는 다시 해당하는 웹페이지에 접속할 때, 브라우저에서 서버로 쿠키를 전송


생성 및 삭제 과정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 쿠키 생성
// getName() 또는 getValue()를 이용하여 쿠키에 접근
Cookie cookie = new Cookie(이름, 값);
response.addCookie(cookie);
 
// 쿠키 확인
// 만약 쿠키값이 없다면 null return
Cookie[] cookies = request.getCookies();
 
// 쿠키 삭제
// 서버는 쿠키를 삭제할 수 없음 ⇨ 클라이언트에게 요청
Cookie cookie = new Cookie(이름, null// 이미 존재하는 쿠키면 덮어쓰기
cookie.setMaxAge(0);
response.addCookie(cookie);
cs


HttpServletRequest와 HttpServletResponse를 사용하여 쿠키 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@GetMapping(path="list")
public String lsit(ModelMap model,
                   HttpServletRequest request,
                   HttpServletResponse response) {
    // Cookie 검사
    String value = null;
    boolean find = false;
    
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("count")){
                value = cookie.getValue();
                find = true;
                break;
            }
        }
    }
 
    // Cookie값 설정
    if(!find){
        value = "1";
    }else {
        try{
            int i = Integer.parseInt(value);
            value = Integer.toString(++i);
        }catch(Exception e){
            value = "1";
        }
    }
 
    // Cookie 설정
    Cookie cookie = new Cookie("count", value);
    cookie.setMaxAge(60*60);
    cookie.setPath("/");    // 경로 이하에 모두 쿠키 적용
    response.addCookie(cookie);
 
    model.addAttribute("cookie",cookie);    
}
cs


@CookieValue를 사용하여 쿠키 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@GetMapping(path="list")
public String lsit(ModelMap model,
                   @CookieValue(value="count", defaultValue="0", required=trueString value,
                   HttpServletResponse response) {
    // Cookie값 설정
    try{            int i = Integer.parseInt(value);
            value = Integer.toString(++i);
        }catch(Exception e){
            value = "1";
        }
    // Cookie 설정
    Cookie cookie = new Cookie("count", value);
    cookie.setMaxAge(60*60);
    cookie.setPath("/");    // 경로 이하에 모두 쿠키 적용
    response.addCookie(cookie);
 
    model.addAttribute("cookie",cookie);    
}
cs



Session

Session이란?

클라이언트 별로 서버에 저장되는 정보


설정 과정

1. Web Client가 WAS에 요청

2. WAS가 클라이언트를 식별하는 sid(session id ) 생성

3. 서버는 sid를 이용해서 세션 저장소(HttpSession) 생성

4. sid를 저장할 수 있는 쿠키를 생성하여 클라이언트에게 전송

5. 클라이언트는 서버측에 요청을 보낼 때, 이 쿠키를 전송하여 요청

6. 서버는 쿠키에 있는 sid를 이용하여 HttpSession을 찾아서 사용


생성 및 삭제 과정

1
2
3
4
5
6
7
8
9
// 세션은 서버측에서 생성!
HttpSession session = request.getSession();            // sid의 쿠키가 있는지?
HttpSession session = request.getSession(true);        // true는 디폴트값
// 서버에 생성된 세션이 있다면 세션 반납, 없다면 새롭게 세션 생성
// false면 null 반환
 
session.setAttribute(이름, 값);
session.getAttribute(이름);
removeAttribute(이름);
cs


@SessionAttribute

메소드에 @SessionAttribute가 있을 경우 파라미터로 지정된 이름으로 등록된 세션 정보를 읽어와서 변수에 할당


@ModelAttribute

@SessionAttribute 파라미터로 지정된 이름과 같은 이름이 @ModelAttribute에 지정되어 있을 경우 메소드가 반환되는 값은 세션에 저장된다


# redirctAttr : dispatcherServlet이 관리하는 FlashMap에 값을 저장


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Controller
public class GuestbookAdminController {
    @GetMapping(path="/loginform")
    public String loginform() {
        return "loginform";
    }
    
    @PostMapping(path="/login")
    public String login(@RequestParam(name="passwd",required=false)String passwd,
                        HttpSession session,
                        RedirectAttributes redirectAttr) {
        if(passwd.equals("1234")) {
            session.setAttribute("isAdmin""true");
        }else {
            redirectAttr.addFlashAttribute("errorMessage","암호가 틀렸습니다.");
            return "redirect:/loginform";
        }
        return "redirect:/list";
    }
    
    @GetMapping(path="/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("isAdmin");
        return "redirect:/list";
    }
}
cs




'Dev > JSP' 카테고리의 다른 글

[JSP] 인터셉터(Interceptor)와 아규먼트 리졸버(Argument Resolver)  (0) 2018.10.10
[JSP] Spring MVC  (0) 2018.07.20
[JSP] Spring JDBC  (0) 2018.07.20
[JSP] Spring  (0) 2018.07.19
[JSP] JDBC 사용하기!!  (0) 2018.05.29