클라이언트가 처음 접근하는 경우 클라이언트가 사용할 세션 아이디를 생성한 후 쿠키를 통해 전달한다. 이렇게 세션 아이디를 한 번 전달하면 이후 요청부터는 상태 값을 공유하기 위해 이 세션 아이디를 사용하면 된다.
RequestHandler 클래스에 세션 아이디가 존재하는지 여부를 판단한 후에 세션 아이디가 존재하지 않을 경우 세션 아이디를 새로 발급한다. 세션 아이디는 JSESSIONID로 전달한다.
- RequestHandler.java
public class RequestHandler extends Thread {
...
public void run() {
log.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(), connection.getPort());
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
HttpRequest request = new HttpRequest(in);
HttpResponse response = new HttpResponse(out);
if (getSessionId(request.getHeader("Cookie")) == null) {
response.addHeader("Set-Cookie", "JSESSIONID=" + UUID.randomUUID());
}
...
} catch (IOException e) {
log.error(e.getMessage());
}
}
private String getSessionId(String cookieValue) {
Map<String, String> cookies = HttpRequestUtils.parseCookies(cookieValue);
return cookies.get("JSESSIONID");
}
}
구현 완료 후 리팩토링 할 부분을 찾아본다. ListUserController 코드에서 로그인 여부를 확인하기 위해 Cookie 헤더 값을 활용하는 부분이 점점 더 증가하고 있다. Cookie 헤더 값을 관리하는 HttpCookie 를 추가하는 것이 좋다.
- HttpCookie.java
import java.util.Map;
import util.HttpRequestUtils;
public class HttpCookie {
private Map<String, String> cookies;
HttpCookie(String cookieValue) {
cookies = HttpRequestUtils.parseCookies(cookieValue);
}
public String getCookie(String name) {
return cookies.get(name);
}
}
위와 같이 HttpCookie 를 추가한 후 HttpRequest 에서 HttpCookie 에 접근할 수 있는 메서드를 추가한다.
- HttpRequest.java
public class HttpRequest {
...
public HttpCookie getCookies() {
return new HttpCookie(getHeader("Cookie"));
}
}
RequestHandler 클래스는 새로 추가한 HttpCookie 를 활용해 다음과 같이 구현할 수 있다.
- RequestHandler.java
public class RequestHandler extends Thread {
...
public void run() {
log.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(), connection.getPort());
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
HttpRequest request = new HttpRequest(in);
HttpResponse response = new HttpResponse(out);
if (request.getCookies().getCookie("JSESSIONID") == null) {
response.addHeader("Set-Cookie", "JSESSIONID=" + UUID.randomUUID());
}
...
} catch (IOException e) {
log.error(e.getMessage());
}
}
...
}
참고도서 : https://roadbook.co.kr/169
[신간안내] 자바 웹 프로그래밍 Next Step
● 저자: 박재성 ● 페이지: 480 ● 판형: 사륙배변형(172*225) ● 도수: 1도 ● 정가: 30,000원 ● 발행일: 2016년 9월 19일 ● ISBN: 978-89-97924-24-0 93000 [강컴] [교보] [반디] [알라딘] [예스24] [인터파크] [샘
roadbook.co.kr
'교재 실습 > 자바 웹 프로그래밍 Next Step' 카테고리의 다른 글
6.3.1 고유한 아이디 생성 (3) | 2025.04.30 |
---|---|
6.2.2 요구사항 분리 및 힌트 (2) | 2025.04.28 |
6.2.1 요구사항 (5) | 2025.04.25 |
6.2 세션(HttpSession) 요구사항 및 실습 (4) | 2025.04.24 |
6.1.5 중복 코드 제거 (2) | 2025.04.23 |
댓글