쿠키의 특징 1. 클라이언트에 저장(서버에 부담 적음) 2. 유효 기간 설정 가능 3. 브라우저에 저장되므로 보안에 상대적으로 취약함 4. 크기 제한 있음(대략 4KB)
쿠키의 동작 흐름 1. 서버가 클라이언트에 쿠키 저장 2. 브라우저는 쿠키 저장 3. 클라이언트가 서버 요청 시 쿠키 자동 전송 4. 서버는 쿠키를 읽고 처리
세션 (Session)
세션은 서버에 저장하는 사용자 정보입니다.
세션의 특징 1. 서버에 저장(더 안전) 2. 서버가 메모리에 저장하므로 서버에 부하 발생할 수 있음 3. 일정 시간 동안 활동 없으면 세션 만료 4. 서버에 있기 때문에 민감한 정보 저장 가능함
세션의 동작 흐름 1. 사용자가 로그인 → 서버가 세션 생성 2. 서버가 세션 ID를 클라이언트에 전달 (보통 쿠키 사용) 3. 사용자는 요청할 때마다 세션 ID 전달 4. 서버는 세션 ID로 사용자 식별
쿠키와 세션의 발전 과정
초창기 웹은 상태가 없는 HTTP 프로토콜 - HTTP는 무상태(Stateless) 프로토콜 - 사용자가 서버에 요청할 때마다 "누가 보냈는지" 알 수 없음 - 서버는 요청을 받을 때마다 매번 새 사용자인지 기존 사용자인지 모름
쿠키의 등장 (1994년, Netscape) - HTTP의 한계를 보완하기 위해 쿠키 등장 -서버가 클라이언트에게 데이터를 저장하게 하고, 이후 요청마다 서버로 자동 전송 -사용자가 서버에 여러 번 접근할 때 같은 사용자라는 걸 알 수 있게 됨 - 장점 : 로그인 유지, 사용자 식별, 맞춤형 서비스 제공 - 단점 : 민감한 정보는 클라이언트에 저장되므로 보안에 취약
세션의 등장 -쿠키만으로는 민감한 정보를 다루기 어려움 -서버에 사용자 정보를 저장하고, 사용자에게는 세션 ID만 전달 -세션 ID는 보통 쿠키에 저장하거나 URL 파라미터로 전달 -서버가 관리하므로 보안이 강화됨 -장점 : 서버에서 관리하므로 보안성 높음 -단점 : 서버 메모리를 사용하므로 사용자가 많아지면 부하 발생
보안 강화를 위한 발전 쿠키와 세션이 널리 쓰이면서 여러 보안 이슈 등장 - 세션 하이재킹 (Session Hijacking) - 쿠키 탈취 (Cross-Site Scripting - XSS) - CSRF (Cross-Site Request Forgery) 보안 옵션 등장 - HttpOnly: JavaScript 접근 제한 - Secure: HTTPS에서만 전송 - SameSite: CSRF 방지 - 세션 관리 기법 발전: 세션 타임아웃, 토큰 갱신, 서버 클러스터링 등
토큰 기반 인증 (JWT 등) - 서버 부하를 줄이고, 분산 시스템에서 인증을 원활히 처리하기 위해 JWT (JSON Web Token) 같은 토큰 기반 인증 방식 등장 - 서버가 상태를 유지하지 않는 방식 (Stateless)으로 인증 가능 - 특히 모바일 앱, 마이크로서비스 아키텍처에서 활발히 사용 - 장점: 서버 메모리 사용 없음, 분산 시스템에 유리 - 단점: 토큰 탈취 시 위험 (만료 시간 및 보안 처리 필수)
JWT (JSON Web Token)
JWT는 서버나 클라이언트가 정보를 JSON 형식으로 저장하고 전달하는 토큰 기반 인증 방식입니다. - JWT는 사용자가 누구인지 증명하는 데 사용되는 토큰입니다. - 토큰 안에 사용자의 정보가 암호화되어 들어 있고, 별도의 세션 저장소 없이 인증할 수 있게 해줍니다.
JWT 구조 : JWT는 총 3부분으로 구성됨 (xxxxx.yyyyy.zzzzz) 1. Header(헤더) - 토큰 타입과 해시 알고리즘 정보
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload(페이로드) - 사용자 정보 (claims) 가 담긴 부분 - 예: 유저 ID, 권한, 토큰 유효 기간 등
3. Signature(서명) -위의 내용이 변조되지 않았음을 증명 - 비밀 키로 생성 (예: HMAC SHA256)
=> 세 부분(1, 2, 3)이 base64로 인코딩되어 하나의 문자열로 만들어짐
JWT의 장점 - Stateless: 서버가 세션을 저장할 필요 없음 - 확장성: 서버가 여러 대여도 세션 공유할 필요 없음 - 빠름: 토큰만 있으면 빠르게 사용자 검증 - 유연성: 모바일/웹/API 어디서나 사용 가능
JWT의 단점 - 토큰 탈취 시 위험: 토큰이 유출되면 악용될 수 있음 - 토큰 폐기 어려움: JWT는 자체적으로 만료 전까지 유효. 서버가 토큰을 즉시 무효화하려면 별도 블랙리스트 관리가 필요 - Payload가 암호화된 것은 아님 (Base64로 인코딩된 것이라 누구나 읽을 수 있음, 민감정보 저장 금지)
브라우저 저장소
저장소
데이터 크기
만료 기간
접근 범위
용도
쿠키 (Cookie)
매우 작음 (~4KB)
설정 가능
서버 & 클라이언트
인증 정보, 세션 식별자 등
Local Storage
크고 (~5MB)
없음 (영구 저장)
클라이언트 전용
사용자 설정, 캐시 데이터 등
Session Storage
Local Storage와 유사 (~5MB)
브라우저 탭이 닫히면 삭제
클라이언트 전용
일회성 데이터, 탭 단위 저장
IndexedDB
매우 큼 (수백 MB 이상)
없음
클라이언트 전용
복잡한 구조화된 데이터 저장 (오프라인 앱 등)
쿠키 (Cookie) - 서버와 함께 사용하는 유일한 저장소 - 매 요청마다 자동으로 서버에 전송됨 - 세션 ID 저장 등 인증 목적으로 많이 사용 - 용량이 적고, 서버로 전송되므로 주의 필요 - 보안 옵션: HttpOnly, Secure, SameSite
HTTP는 하이퍼텍스트(HTML 문서 등)를 웹 브라우저와 서버 간에 주고받기 위한 프로토콜입니다.
HTTP는 웹 처리 전반에 걸친 토대가 되기 때문에 웹 서버를 HTTP 서버라고 부르기도 합니다.
HTTP의 동작 방식 1. 클라이언트(브라우저)가 요청(Request) - URL 입력 → HTTP 요청 전송 (예: GET /index.html HTTP/1.1) 2. 서버가 응답(Response) - 요청받은 웹 페이지나 파일을 HTTP 응답으로 반환
HTTP의 특징 1. 텍스트 기반 : 사람이 읽을 수 있는 텍스트 형식 2. Stateless(무상태) : 요청과 응답이 독립적 3. 확장성 : 다양한 데이터 형식 전송 가능 (HTML, 이미지, 동영상 등) 4. 포트 번호 : 기본 포트 80
HTTPS(HyperText Transfer Protocol Secure) 란?
HTTPS는 웹에서 데이터를 안전하게 주고받기 위한 프로토콜 HTTP에 SSL/TLS 암호화가 추가된 형태입니다. 보안성, 신뢰성, 사용자 보호 강화를 위해 대부분의 웹사이트가 HTTPS 사용 중입니다.
HTTPS의 동작 방식 1. 브라우저에서 HTTPS 주소 입력 (예: https://example.com) 2. 서버가 인증서(SSL/TLS)를 제공 3. 브라우저가 인증서 유효성 검증 4. 데이터 암호화 후 통신 시작
HTTPS의 주요 특징 1. 암호화 (Encryption) : SSL/TLS 기술로 통신 데이터를 암호화해서 중간에 탈취되어도 내용을 알 수 없음 2. 인증 (Authentication) : 신뢰할 수 있는 기관(CA)으로부터 서버 인증서를 발급받아, 서버의 신원을 검증 3. 무결성 (Integrity) : 데이터가 전송 중 변조되지 않았음을 보장 4. 포트 번호 : 기본 포트 443
HTTP 와 HTTPS
구분
HTTP
HTTPS
전체 이름
HyperText Transfer Protocol
HyperText Transfer Protocol Secure
보안성
🔓 암호화 없음
🔒 SSL/TLS 암호화 적용
사용 포트
80
443
데이터 보호
전송 중 데이터 노출 가능
전송 중 데이터 암호화
신뢰성
상대적으로 낮음
인증서로 신원 검증 가능
사용 예
단순 정보 조회
로그인, 결제 등 민감한 데이터 처리 시 필수
HTTP 헤더, 바디의 구조
HTTP 메시지는 요청(Request), 응답(Response) 및 헤더(Header) 와 바디(Body) 로 나눌 수 있습니다. 1. HTTP 요청(Request) - 시작줄 (Start Line) 예 : GET /index.html HTTP/1.1 의미 : index.html 파일을 가져와주세요 - 헤더 (Headers) 추가적인 정보 전달 (key: value 형식) 예: Host: http://www.example.com User-Agent: Mozilla/5.0 Accept: text/html - 바디 (Body) 선택 사항 데이터 전송 시 사용 (예: POST 요청에서 폼 데이터) 예: username=chatgpt&password=secure 2. HTTP 응답(Response) - 상태줄 (Status Line) 예 : HTTP/1.1 200 OK 의미 : 요청 성공적으로 처리했어요 - 헤더 (Headers) 응답 정보 제공 예: Content-Type: text/html Content-Length: 3057 - 바디 (Body) 실제 컨텐츠 (HTML, JSON 등) 예: <html> <body> <h1>Welcome!</h1> </body> </html>
HTTP Method
1. GET 방식
-데이터가 주소 입력란에 표시되므로 최소한의 보안도 유지되지 않는 취약한 방식
- 가장 일반적인 HTTP Request 형태로, 요청 데이터의 인수를 웹 브라우저의 URL로 전송 - 예시 : 웹 페이지 보기, 이미지 로딩
2.POST 방식
-인숫값을 URL로 전송하지 않으므로 다른 사용자가 링크로 해당 페이지를 볼 수 없음
-게시판의 경우: 목록이나 글 보기 화면은 접근 자유도를 위해 GET 방식을 사용 게시글을 저장·수정·삭제하거나 대용량 데이터를 전송할 때는 POST 방식을 사용
-URL에 요청 데이터를 기록하지 않고 HTTP 헤더에 데이터를 전송 - 예시 : 회원가입, 로그인
3. 기타 방식
-OPTIONS 방식: 자원에 대한 요구/응답 관계와 관련된 선택 사항 정보를 요청할 때 사용 예시 : 서버 기능 점검
-DELETE 방식: URI에 지정된 자원을 서버에서 지울 수 있게 함 예시 : 게시글 삭제
-PUT 방식: 메시지에 포함된 데이터를 지정된 URI 장소에 그 이름으로 저장 예시 : 게시글 전체 수정
-HEAD 방식: 서버 측 데이터를 검색하고 요청하는 데 사용 예시 : 리소스 존재 여부 확인 - PATCH 방식 : 서버의 데이터를 부분 수정하는 데 사용 예시 : 댓글 일부 수정 -TRACE 방식: 요구 메시지의 최종 수신처까지 루프백을 검사하는 데 사용
HTTP 상태코드
HTTP Response - 클라이언트의 HTTP Request에 대한 응답 패킷 - 서버에서 쓰이는 프로토콜 버전, Request에 대한 실행 결과 코드, 간략한 실행 결과 설명문 내용이 담겨 있음 - 추가 정보로 전달할 데이터 형식, 길이 등이 MIME 형식으로 표현되어 있음 - 헤더 정보 뒤에는 실제 데이터(HTML 또는 이미지 파일)가 전달됨 - 데이터 전달이 끝나면 서버 연결을 끊음
실행 결과 코드
내용
설명
100번대
정보 전송
HTTP 1.0까지는 계열에 대한 정의가 이루어지지 않았기 때문에 실험 용도 외에는 100번대 서버 측의 응답이 없다.
200번대
성공
클라이언트의 요구가 성공적으로 수신 및 처리되었음을 의미한다.
300번대
리다이렉션
해당 요구 사항을 처리하기 위해 사용자 에이전트가 수행해야 할 추가 동작이 있음을 의미한다.
400번대
클라이언트 측 에러
클라이언트에 오류가 발생했을 때 사용한다. 예를 들면 클라이언트가 서버에 보내는 요구 메시지를 완전히 처리하지 못한 경우 등이다.
500번대
서버 측 에러
서버 자체에서 발생한 오류 상황이나 요구 사항을 제대로 처리할 수 없을 때 사용한다.
SSL (Secure Sockets Layer) 인증서
SSL 인증서는 웹사이트와 사용자의 브라우저 간에 오가는 데이터를 암호화해서 정보를 안전하게 보호하는 기술입니다.
현재는 SSL의 후속 버전인 TLS (Transport Layer Security) 가 더 많이 사용됩니다.
SSL 인증서가 왜 필요할까? 1. 데이터 암호화 : 비밀번호, 신용카드 정보 등 민감한 데이터 보호 2. 중간자 공격 방지 : 데이터가 가로채이더라도 해독 불가능 3. 신뢰성 확보 : 주소창의 자물쇠 아이콘, HTTPS 사용으로 사용자의 신뢰 확보 4. SEO 효과 : 구글 등 검색 엔진이 보안이 강화된 사이트를 우선 노출
SSL 인증서 작동 방식 1. 클라이언트가 서버에 접속 → 안전한 통신을 위한 요청 2. 서버가 SSL 인증서 전달 3. 클라이언트가 유효성 검증 4. 공개키 기반으로 암호화된 세션 키 전달 5. 이후 세션 키로 양방향 암호화 통신!
SSL 인증서 종류
종류
설명
DV (Domain Validation)
도메인 소유 여부만 확인
OV (Organization Validation)
기업 정보까지 검증
EV (Extended Validation)
가장 강력! 기업 법적 존재 여부까지 검증, 주소창에 회사명 표시
실습
curl을 이용하여 HTTP요청 직접 보내보기
curl 이란? - curl은 command-line tool (명령줄 도구)로, URL을 통해 데이터를 전송하거나 받아올 수 있게 도와주는 프로그램이고, "Client URL" 의 줄임말입니다
curl 사용법
옵션
설명
-X
HTTP 메서드 지정 (GET, POST, PUT, DELETE 등)
-d
요청 데이터 (POST, PUT 등)
-H
요청 헤더 추가
-F
파일 전송 (multipart/form-data)
-o
출력 파일 이름 지정
-O
원래 이름으로 파일 저장
-I
응답 헤더 출력
-L
리다이렉션 따라가기
-u
기본 인증 (user:password)
-c / -b
쿠키 저장 / 사용
1. Google 메인 페이지 GET 요청
curl -L https://google.com
2. 응답 헤더만 보기
curl -I https://google.com
3. 파일로 저장해보기
curl -L -o google.html https://google.com
# 저장된 파일 확인
cat google.html
4. User-Agent 변경해서 요청
curl -L -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://google.com
5. HTTPS 인증서 정보 확인
curl -v https://google.com
# 또는 더 자세히
curl -vI https://google.com
6. HTTP/2 로 요청
- 윈도우 CMD 환경에서 실행 시
curl: option --http2: the installed libcurl version does not support this curl: try 'curl --help' for more information 오류가 뜨며 리눅스에서 실행하였습니다.
- 원인은 현재 윈도우에 깔려 있는 curl이 HTTP/2 프로토콜을 지원하지 않는다고 합니다.
#vi 편집기로 curl- format.txt 만들기
vi curl-format.txt
# 아래 명령어 입력 후 저장하기
melookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
- curl-format.txt를 만든 후 아래 명령어를 실행하면 실행 결과를 확인할 수 있다.
프로토콜은 컴퓨터나 네트워크 장비들 사이에서 데이터를 주고받을 때 지켜야 하는 약속(규칙)입니다.
프로토콜의 3가지 요소 1. 구문(Syntax): 데이터의 구조나 포맷을 의미 2. 의미(Semantics): 전송되는 데이터의 각 부분이 무엇을 뜻하는지 를 알 수 있게 미리 정해 둔 규칙(데이터 자체 뿐만 아니라 오류 제어, 동기 제어, 흐름 제어를 포함) 3. 순서(Timing): 어떤 데이터를 보낼 것인지와 얼마나 빠르게 데이 터를 보낼 것인지 정의
프로토콜의 기능 1. 주소 설정(Addressing): 서로 다른 시스템의 두 개체가 통신을 하는 경우 필요 2. 순서 제어(Sequence Control): 프로토콜 데이터 단위를 전송할 때 보내는 순서를 명시하는 기능(연결 지향형(Connection-Oriented)에만 사용) 3. 데이터 분할과 재조합(Fragmentation & Reassembly): 대용량 파일을 전송할 때 전송 효율이 높은 작은 단위로 나누어 전송한 뒤 전송 받은 시스템에서 이를 재조합해야 함 4. 캡슐화(Encapsulation): 데이터에 제어 정보를 덧붙이는 것(헤더) 5. 연결제어(Connection Control): 연결 설정, 데이터 전송, 연결 해제에 대한 통제 수행 6. 흐름 제어(Flow Control): 송신 측에서 오는 데이터의 양이나 속도를 조절하는 기능, 송신자와 수신자의 속도 차이에 대한 대응 7. 오류 제어(Error Control): 두 개체 사이에서 데이터를 교환할 때 데이터에 오류나 변경이 있을 경우를 발견하는 기능 8. 동기화(Synchronization): 두 개체 데이터를 교환할 때 서로 동시에 똑같이 정의된 인자 값 을 공유하는 것 정보를 송수신 할 때에 호흡을 맞추는 기능 9. 다중화(Multiplexing): 통신 선로 하나에서 여러 데이터나 시스템을 동시에 통신할 수 있는 기법 10. 전송 서비스(Quality of Service, QoS): 우선 순위 결정, 서비스 등급과 보안 요구 등을 제어하는 서비스
OSI 7 계층
OSI 7 계층은 네트워크에서 데이터를 주고받을 때의 과정을 7단계로 나눈 모델입니다.
OSI 7 계층은 물리 계층, 데이터 링크 계층, 네트워크 계층, 전송 계층, 세션 계층, 표현 계층, 응용 계층으로 나뉩니다.
사용자 기반 계층
응용 계층(Application Layer)
사용자 인터페이스 제공.요구에 따른 정보처리
표현 계층(Presentation Layer)
전달되는 정보를 데이터로 표현,암호화,압축
세션 계층(Session Layer)
통신 시작,유지/관리,종료
트랜스포트 계층
전송 계층(Transport Layer)
종단간(응용 프로세스 간)신뢰성 있는 메시지 전송(에러제어,흐름제어,혼잡제어)
네트워크 기반 계층
네트워크 계층(Network Layer)
Datagram을 발신지(노드)에서 목적지(노드)까지 전달(라우팅)
데이터링크 계층(DataLink Layer)
노드간(물리적으로 연결된)신뢰성 있는 전송 제공(에러제어,흐름제어,혼잡제어)
물리 계층(Physical Layer)
물리매체로 비트를 신호로 변경하여 전송(부호화,기계적,전기적 특성 제공)
TCP(Transmission Control Protocol)
TCP는 데이터를 안정적으로 전송하는 연결 지향형 프로토콜이고, IP와 함께 통신을 하는 데 반드시 필요한 가장 기본적인 프로토콜입니다.
TCP의 특징 높은 신뢰성 1. 가상 회선 연결 방식 2. 연결의 설정과 해제 3. 데이터 체크섬(Checksum) 4. 시간 초과와 재전송 5. 데이터 흐름 제어
UDP(User Datagram Protocol)
UDP는 빠르게 데이터를 전송하는 비연결 지향형 프로토콜입니다.
상대방이 보낸 응답을 확인하지 않아 네트워크에 부하를 주지 않습니다. 데이터 자체의 신뢰성이 없어 수신한 데이터의 무결성을 보장받지 못합니다.
UDP의 특징 1. 비연결 지향형 2. 네트워크 부하 감소 3. 비신뢰성 4. 전송된 데이터의 일부가 손실
TCP와 IP의 연계
TCP/IP는 인터넷에서 데이터를 전송하는 표준 프로토콜 세트입니다.
쉽게 설명하면, IP는 데이터 패킷이 목적지까지 가도록 안내하는 네비게이션 역할 TCP는 데이터가 정확히 도착했는지 확인하고, 순서를 맞춰주는 역할입니다. - IP (Internet Protocol) → 목적지까지 데이터 패킷을 전달하는 역할 (주소 지정 & 라우팅). → 데이터가 어디서 어디로 가야 하는지 알려주는 "배달 주소 역할 - TCP (Transmission Control Protocol) → IP가 전달하는 데이터의 전송 품질을 보장하는 역할 (순서 보장, 오류 검사, 재전송). → 데이터를 안정적으로 주고받기 위한 안전한 배달 서비스 역할
TCP/IP의 데이터 전송 흐름 1. TCP가 데이터를 분할 2. IP가 패킷에 주소를 부여 3. 수신 측에서 재조립
3-Way Handshake
TCP 프로토콜은 데이터 전송 전에 안전하고 신뢰성 있는 연결을 위해 3단계 과정(3-Way Handshake)을 사용합니다.
TCP 3-Way Handshake 연결 동작 과정 1. 클라이언트 → 서버 : SYN - 클라이언트가 서버에게 연결 요청을 보냄 - SYN 패킷(Synchronize) 전송 2. 서버 → 클라이언트 : SYN + ACK - 서버가 요청을 받고, 연결 요청을 응답 - SYN (동기화) + ACK (확인 응답) 패킷 전송 3. 클라이언트 → 서버 : ACK - 클라이언트가 서버에게 다시 잘받았다는 것을 응답 - 연결 완료
4-Way Handshake
연결을 종료할 때도 안전하게 연결을 종료하기 위해 사용하는 4단계 과정(4-Way Handshak)을 사용합니다.
TCP 4-Way Handshake 연결 동작 과정 1. 클라이언트 → 서버 : FIN - 클라이언트가 연결 종료를 요청 - FIN (Finish) 패킷 전송 2. 서버 → 클라이언트 : ACK - 서버가 확인 응답 - ACK (Acknowledgment) 패킷 전송 3. 서버 → 클라이언트 : FIN - 서버도 데이터를 전부 전송하고 종료 요청 - FIN 패킷 전송 4. 클라이언트 → 서버 : ACK - 클라이언트가 마지막 응답을 보냄 - 연결 종료
IPv4, IPv6
IPv4, IPv6는 인터넷 통신을 위한 프로토콜(규칙)의 버전이며, 각각 32bit, 128bit의 주소 공각을 사용합니다.
IPv4는 인터넷의 초기 버전으로, 현재도 많이 사용되고 있지만 주소 부족의 문제로 IPv6가 개발되었습니다.
주소 부족: 약 43억 개 주소로 제한, 이미 거의 소진됨 보안: IPSec 보안 기능은 선택 사항 (기본 제공 X) NAT 필요: 여러 기기가 하나의 IP를 공유해야 함 확장성 부족: 기기 수 증가에 따른 한계
전환 복잡성: 기존 IPv4에서 IPv6로의 전환 필요 호환성 문제: 일부 오래된 장비나 소프트웨어는 IPv6 미지원
장점
간편한 설정: IPv4는 오래 사용되어 익숙하고 관리가 쉬움 광범위한 호환성: 대부분의 네트워크 장비 및 시스템이 IPv4 지원
거대한 주소 공간: 사실상 무제한의 IP 주소 자동 구성: Stateless Address Autoconfiguration (SLAAC) 보안: IPSec 기본 제공 빠른 라우팅 및 멀티캐스트 지원
DNS란? (Domain Name System)
DNS는 도메인 이름을 IP 주소로 변환해주는 시스템입니다. 사람이 기억하기 쉬운 도메인 이름(예: www.example.com)을 컴퓨터가 이해할 수 있는 IP 주소(192.0.2.1)로 변환합니다.
DNS의 동작 원리 1. 사용자가 웹 브라우저에 도메인 이름 입력 2. DNS 서버가 도메인 이름을 IP 주소로 변환 3. 변환된 IP 주소를 이용해 웹 서버 접속 4. 원하는 웹 페이지 전달
DNS의 계층 구조 - 가장 상위 개체는 ‘.’ (Root) - 두 번째 개체는 국가와 조직체의 특성 - 보통 맨 앞은 자신의 DNS 서버에서 지정해 놓은 www, ftp와 같은 특정 서버의 이름이 옴 - FQDN(Fully Qualified Domain Name) : 완성된 주소(예: www.example.com)
항목
내용
항목
내용
com
영리 기관
mil
군사 기관
net
네트워크 기관
edu
교육 기관
org
비영리 기관
int
국제 기관
gov
정부 기관
kr(Korea)
국가 이름
DNS의 계층 구조
DNS 서버의 이름 해석 순서 DNS 서버의 이름 해석 순서
www.wishfree.com 에 접속하기 위한 순서 1 | 캐시에 해당 사이트 정보를 확인 2 | 캐시에 IP주소가 없을 경우에 hosts를 확인 3 | 없으면 설정된 DNS 서버인 로컬 DNS 서버에 질의 4 | 로컬 DNS에 없으면 루트 DNS에 질의 5 | com DNS 서버에 질의 6 | com DNS에도 없다면, wishfree.com DNS 서버에 질의 7 |www.wishfree.com에대한 IP 주소를 얻음 8 | 로컬 DNS 서버는 이를 클라이언트에 전달
포트
포트는 네트워크에서 특정 서비스를 구분하는 논리적인 출입구입니다. IP 주소가 "어느 컴퓨터"인지를 알려준다면, 포트 번호는 "어떤 프로그램(서비스)"인지를 구분합니다.
포트의 기능 - 하나의 IP 주소에서 여러 서비스를 구분 - 서버는 포트를 열어 두고 요청을 기다림 - 클라이언트는 목적지 IP + 포트로 요청
대표적인 포트 예시
서비스
포트
설명
HTTP
80
웹 사이트 접속 (보안 없음)
HTTPS
443
암호화된 웹 접속 (보안 HTTPS)
FTP
21
파일 전송 프로토콜
SSH
22
원격 접속 (보안 쉘)
DNS
53
도메인 이름 서비스
SMTP
25
이메일 송신
포트포워딩
포트포워딩은 외부에서 내부 네트워크의 특정 기기나 서비스에 접근할 수 있도록 라우터에서 포트를 지정하여 연결하는 기술입니다.
포트포워딩이 왜 필요한가? 1. 내부 네트워크(사설 IP)는 외부 인터넷에서 직접 접근 불가능 2. 포트 포워딩을 통해 외부 요청을 내부 장비로 연결
포트포워딩의 동작 원리 1. 외부 요청: 외부에서 공인 IP + 포트로 요청 2. 라우터 확인: 포트 포워딩 규칙에 따라 내부 IP + 포트로 전달 3. 내부 장비 응답: 요청받은 내부 장비가 응답
웹은" 월드 와이드 웹(WWW, World Wide Web)"의 줄임말로, 인터넷을 통해 정보를 주고받을 수 있게 만든 정보 공유 시스템이며, "인터넷"이라는 통신망을 이용한 하나의 서비스입니다.
아래의 그림과 같이 사용자는웹브라우저로 접속하고,인터넷을 통하여 웹서버는 요청받은웹페이지(HTML, 이미지 등)를 보내주게 됩니다.
인터넷(Internet)
인터넷이란 인터 네트워크(Inter-network)이며, 네트워크 간의를 의미하고네트워크와 네트워크를 연결한다라는 의미로 쓰입니다.
전 세계가 연결되어있는 거대한 통신망을 의미하며, 실체는 존재하지 않는 추상적인 개념이며, 중앙 집중적이지 않고, 매우 복잡하게 얽힌 통신망입니다.
유추해볼 수 있듯이 인터넷은 바로네트워크간의 연결,네트워크의 네트워크라는 뜻을 지니고 있습니다.
웹 서버(Web Server)
웹 서버는 웹사이트의 데이터를 저장하고, 사용자가 요청하면 웹페이지(HTML, 이미지 등)를 전달해 주는 컴퓨터나 프로그램입니다.
웹 서버는 하드웨어와, 소프트웨어의 구성으로 나눌 수 있습니다. - 하드웨어 : 웹사이트 데이터를 저장하는 실제 컴퓨터 - 소프트웨어 : 요청을 처리하고, 웹페이지를 전달하는 프로그램
웹 서버의 작동 원리 1. 요청(Request) : 사용자가 브라우저에 주소(www.example.com)를 입력하거나 클릭해서 요청을 보냄 2. 처리(Process) : 웹 서버가 요청을 받고, 해당 페이지가 있는지 확인 3. 응답(Response) : HTML 문서, 이미지, CSS 파일 등을 찾아서 사용자에게 전송 4. 브라우저 표시 : 사용자의 웹브라우저가 웹 서버에서 받은 정보를 화면에 표시
웹 브라우저(Web Browser)
웹 브라우저는 웹 서버에서 받은 정보를 사용자에게 보기 쉽게 보여주는 프로그램이며, 브라우저 덕분에 우리는 인터넷을 사용할 때 모든 웹페이지를 볼 수 있습니다.
웹 브라우저는 Google Chrome, Safari, Microsoft Edge, Mozilla Firefox 등이 있습니다.
웹 브라우저의 작동 원리 1. URL 입력 : 사용자가 브라우저 주소창에 https://www.example.com 을 입력 2. 서버 요청(Request) : 브라우저가 입력한 주소에 해당하는 웹 서버에 요청을 보냄 3. 서버 응답(Response) : 웹 서버가 HTML, CSS, JavaScript, 이미지 등 파일을 브라우저에게 전달 4. 렌더링(Rendering) : 브라우저가 받은 파일들을 해석하여 우리가 보는 화면으로 예쁘게 구성 5. 사용자 인터랙션 : 사용자는 웹페이지를 클릭하거나 스크롤하면서 서버와 계속 소통
서버(Server), 클라이언트(Client)
서버(Server)는 다른 컴퓨터(클라이언트)에게 정보를 제공하거나 서비스를 제공하는 컴퓨터나 프로그램입니다. 쉽게 말하면, 누군가가 요청하면 필요한 데이터를 찾아서 전달하는 역할을 수행합니다. 서버의 예시로는 웹 서버(Apache, Nginx), 메일 서버, 파일 서버, 게임 서버 등이 있습니다.
클라이언트(Client)는 서버에 요청을 보내고, 서버가 보내주는 정보를 사용하는 프로그램이나 장치입니다. 클라이언트의 예시로는 웹 브라우저(크롬, 사파리, 엣지 등), 이메일 앱(Gmail, Outlook 등), 게임 클라이언트(롤, 배틀그라운드) 등이 있습니다.
package com.market.main;
public class Welcome {
public static void main(String[] args) {
new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
}
}
com.market.main 패키지
- GuestWindow 클래스 수정
package com.market.main;
import javax.swing.*;
import java.awt.*;
import com.market.member.UserInIt;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuestWindow extends JFrame {
public GuestWindow(String title, int x, int y, int width, int height) {
initContainer(title, x, y, width, height); // initContainer() 메서드 호출
setVisible(true); // 프레임 보이기 설정
setResizable(true); // 프레임 크기 조절 가능 설정
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
}
private void initContainer(String title, int x, int y, int width, int height) {
setTitle(title); // 프레임 제목 설정
setBounds(x, y, width, height); // 프레임 위치, 크기 설정
setLayout(null); // 프레임 레이아웃 미설정
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
// user.png 이미지 표시를 위한 패널 영역 설정 및 출력
JPanel userPanel = new JPanel();
userPanel.setBounds(0, 100, 1000, 256);
ImageIcon imageIcon = new ImageIcon("src/images/user.png"); // ./images/user.png 이미지 불러오지 못함
imageIcon.setImage(imageIcon.getImage().getScaledInstance(160, 160, Image.SCALE_SMOOTH));
JLabel userLabel = new JLabel(imageIcon);
userPanel.add(userLabel);
add(userPanel);
// -- 고객 정보를 입력하세요 -- 표시를 위한 패널 영역 설정 및 출력
JPanel titlePanel = new JPanel();
titlePanel.setBounds(0, 350, 1000, 50);
add(titlePanel);
JLabel titleLabel = new JLabel("-- 고객 정보를 입력하세요 --");
titleLabel.setFont(ft); // JLabel인 titleLabel 글꼴 설정
titleLabel.setForeground(Color.BLUE); // JLabel인 titleLabel 문자열 색상 설정
titlePanel.add(titleLabel);
// 이름 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 400, 1000, 50);
add(namePanel);
JLabel nameLabel = new JLabel("이 름 : ");
nameLabel.setFont(ft);
namePanel.add(nameLabel);
// 이름 표시를 위한 패널 영역 설정 및 출력
JTextField nameField = new JTextField(10);
nameField.setFont(ft);
namePanel.add(nameField);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 450, 1000, 50);
add(phonePanel);
JLabel phoneLabel = new JLabel("연락처 : ");
phonePanel.setFont(ft);
phonePanel.add(phoneLabel);
JTextField phoneField = new JTextField(10);
phonePanel.setFont(ft);
phonePanel.add(phoneField);
// <쇼핑하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 500, 1000, 100);
add(buttonPanel);
JLabel buttonLabel = new JLabel("쇼핑하기", new ImageIcon("src/images/shop.png"), JLabel.LEFT); // images/shop.png 이미지 불러오지 못함
buttonLabel.setFont(ft);
JButton enterButton = new JButton();
enterButton.add(buttonLabel);
buttonPanel.add(enterButton);
enterButton.addActionListener(new ActionListener() { // 쇼핑하기 버튼의 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
JLabel message = new JLabel("고객 정보를 입력하세요");
if(nameField.getText().isEmpty() || phoneField.getText().isEmpty()) // 이름 또는 연락처를 입력하지 않았을 때 오류 메시지 대화상자 표시
JOptionPane.showMessageDialog(enterButton, message, "고객정보", JOptionPane.ERROR_MESSAGE);
else { // 이름 또는 연락처를 입력했을 때 온라인 서점 프레임 생성 호출
UserInIt.init(nameField.getText(), Integer.parseInt(phoneField.getText())); // 입력한 고객 정보 저장
dispose(); // 대화상자 닫기
new MainWindow("온라인 서점", 0, 0, 1000, 750);
// MinWindow 프레임 호출
}
}
});
}
}
- MainWindow 클래스 수정
package com.market.main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.market.page.GuestInfoPage;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.market.cart.Cart;
import com.market.bookitem.BookInIt;
import com.market.page.CartAddItemPage;
import com.market.page.CartItemListPage;
import com.market.page.CartShippingPage;
import com.market.page.AdminLoginDialog;
import com.market.page.AdminPage;
public class MainWindow extends JFrame {
static Cart mCart;
static JPanel mMenuPanel, mPagePanel;
public MainWindow(String title, int x, int y, int width, int height) {
initContainer(title, x, y, width, height); // initContainer() 메서드 호출
initMenu();
setVisible(true); // 프레임 보이기 설정
setResizable(true); // 프레임 크기 조절 가능 설정
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
}
private void initContainer(String title, int x, int y, int width, int height) {
setTitle(title);
; // 프레임 제목 설정
setBounds(x, y, width, height); // 프레임 위치, 크기 설정
setLayout(null); // 프레임 레이아웃 미설정
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
mMenuPanel = new JPanel();
mMenuPanel.setBounds(0, 20, width, 130);
menuIntroduction();
add(mMenuPanel);
mPagePanel = new JPanel();
mPagePanel.setBounds(0, 150, width, height);
add(mPagePanel);
this.addWindowListener(new WindowAdapter() { // 프레임 닫기 버튼 클릭 이벤트 처리
@Override
public void windowClosed(WindowEvent e) {
setVisible(false); // 현재 프레임 감추기
new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
}
});
}
private void menuIntroduction() {
mCart = new Cart();
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
JButton bt1 = new JButton("고객 정보 확인하기", new ImageIcon("src/images/1.png"));
bt1.setBounds(0, 0, 100, 50);
bt1.setFont(ft);
mMenuPanel.add(bt1);
// <고객 정보 확인하기> 버튼 표시를 위한 패널 영역 설정 및 출력
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mPagePanel.removeAll(); // 패널(mPagePanel)에 표시된 구성 요소 모두 삭제
mPagePanel.add("고객 정보 확인", new GuestInfoPage(mPagePanel)); // 패널(mPagePanel)에 GuestInfoPage의 내용 출력
mPagePanel.revalidate(); // 구성 요소 가로/세로 속성 변경하여 호출
mPagePanel.repaint(); // 구성요소 모양을 변경하여 호출
}
});
JButton bt2 = new JButton("장바구니 상품목록보기", new ImageIcon("src/images/2.png"));
bt2.setBounds(0, 0, 100, 30);
bt2.setFont(ft);
mMenuPanel.add(bt2);
// <장바구니 상품 목록보기> 버튼 표시를 위한 패널 영역 설정 및 출력
bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(bt2, "장바구니에 항목이 없습니다", "장바구니 상품 목록 보기", JOptionPane.ERROR_MESSAGE);
else {
mPagePanel.removeAll();
mPagePanel.add("장바구니 상품 목록 보기", new CartItemListPage(mPagePanel, mCart));
mPagePanel.revalidate();
mPagePanel.repaint();
}
}
});
// <장바구니 비우기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt3 = new JButton("장바구니 비우기", new ImageIcon("src/images/3.png"));
bt3.setBounds(0, 0, 100, 30);
bt3.setFont(ft);
mMenuPanel.add(bt3);
bt3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(bt3, "장바구니에 항목이 없습니다", "장바구니 비우기", JOptionPane.ERROR_MESSAGE);
else {
mPagePanel.removeAll();
menuCartClear(bt3);
mPagePanel.add("장바구니 비우기", new CartItemListPage(mPagePanel, mCart));
mPagePanel.revalidate();
mPagePanel.repaint();
}
}
});
// <장바구니에 항목 추가하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt4 = new JButton("장바구니에 항목추가하기", new ImageIcon("src/images/4.png"));
bt4.setFont(ft);
mMenuPanel.add(bt4);
bt4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mPagePanel.removeAll();
BookInIt.init();
mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
mPagePanel.revalidate();
mPagePanel.repaint();
}
});
// <장바구니의 항목 수량 줄이기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt5 = new JButton("장바구니에 항목수량 줄이기", new ImageIcon("src/images/5.png"));
bt5.setFont(ft);
mMenuPanel.add(bt5);
// <장바구니의 항목 삭제하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt6 = new JButton("장바구니에 항목삭제하기", new ImageIcon("src/images/6.png"));
bt6.setFont(ft);
mMenuPanel.add(bt6);
bt6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(bt3, "장바구니에 항목이 없습니다", "장바구니 비우기", JOptionPane.ERROR_MESSAGE);
else {
mPagePanel.removeAll();
CartItemListPage cartList = new CartItemListPage(mPagePanel, mCart);
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(bt6, "장바구니에 항목이 없습니다");
else if (cartList.mSelectRow == -1)
JOptionPane.showMessageDialog(bt6, "장바구니에서 삭제할 항목을 선택하세요");
else {
mCart.removeCart(cartList.mSelectRow);
cartList.mSelectRow = -1;
}
}
mPagePanel.add("장바구니의 항목 삭제하기", new CartItemListPage(mPagePanel, mCart));
mPagePanel.revalidate();
mPagePanel.repaint();
}
});
// <주문하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt7 = new JButton("주문하기", new ImageIcon("src/images/7.png"));
bt7.setFont(ft);
mMenuPanel.add(bt7);
bt7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(bt7, "장바구니에 항목이 없습니다", "주문처리", JOptionPane.ERROR_MESSAGE);
else {
mPagePanel.removeAll();
mPagePanel.add("주문 배송지", new CartShippingPage(mPagePanel, mCart));
mPagePanel.revalidate();
mPagePanel.repaint();
}
}
});
// <종료> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt8 = new JButton("종료", new ImageIcon("src/images/8.png"));
bt8.setFont(ft);
mMenuPanel.add(bt8);
bt8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int select = JOptionPane.showConfirmDialog(bt8, "쇼핑몰을 종료하겠습니까? ");
if (select == 0) {
System.exit(1);
}
}
});
// <관리자> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt9 = new JButton("관리자", new ImageIcon("src/images/9.png"));
bt9.setFont(ft);
mMenuPanel.add(bt9);
bt9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AdminLoginDialog adminDialog;
JFrame frame = new JFrame();
adminDialog = new AdminLoginDialog(frame, "관리자 로그인");
adminDialog.setVisible(true);
if (adminDialog.isLogin) {
mPagePanel.removeAll();
mPagePanel.add("관리자", new AdminPage(mPagePanel));
mPagePanel.revalidate();
mPagePanel.repaint();
}
}
});
}
private void initMenu() {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
JMenuBar menuBar = new JMenuBar();
JMenu menu01 = new JMenu("고객");
menu01.setFont(ft);
JMenuItem item01 = new JMenuItem("고객 정보");
JMenuItem item11 = new JMenuItem("종료");
menu01.add(item01);
menu01.add(item11);
menuBar.add(menu01);
JMenu menu02 = new JMenu("상품");
menu02.setFont(ft);
JMenuItem item02 = new JMenuItem("상품 목록");
menu02.add(item02);
menuBar.add(menu02);
JMenu menu03 = new JMenu("장바구니");
menu03.setFont(ft);
JMenuItem item03 = new JMenuItem("항목 추가");
JMenuItem item04 = new JMenuItem("항목 수량 줄이기");
JMenuItem item05 = new JMenuItem("항목 삭제하기");
JMenuItem item06 = new JMenuItem("장바구니 비우기");
menu03.add(item03);
menu03.add(item04);
menu03.add(item05);
menu03.add(item06);
menuBar.add(menu03);
JMenu menu04 = new JMenu("주문");
menu04.setFont(ft);
JMenuItem item07 = new JMenuItem("영수증 표시");
menu04.add(item07);
menuBar.add(menu04);
setJMenuBar(menuBar);
item01.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mPagePanel.removeAll();
mPagePanel.add("고객 정보 확인 ", new GuestInfoPage(mPagePanel));
add(mPagePanel);
mPagePanel.revalidate();
}
});
item02.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mPagePanel.removeAll();
BookInIt.init();
mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
add(mPagePanel);
mPagePanel.revalidate();
}
});
item11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mPagePanel.removeAll();
setVisible(false);
new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
add(mPagePanel);
mPagePanel.revalidate();
}
});
}
private void menuCartClear(JButton button) {
if (mCart.mCartCount == 0)
JOptionPane.showMessageDialog(button, "장바구니의 항목이 없습니다");
else {
int select = JOptionPane.showConfirmDialog(button, "장바구니의 모든 항목을 삭제하겠습니까? ");
if (select == 0) {
mCart.deleteBook();
JOptionPane.showMessageDialog(button, "장바구니의 모든 항목을 삭제했습니다");
}
}
}
}
com.market.page 패키지
- GuestInfoPage 클래스 수정
package com.market.page;
import javax.swing.*;
import com.market.member.UserInIt;
import java.awt.*;
public class GuestInfoPage extends JPanel {
public GuestInfoPage(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
// 이름 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 100, 1000, 50);
add(namePanel);
JLabel nameLabel = new JLabel("이 름 : ");
nameLabel.setFont(ft);
nameLabel.setBackground(Color.BLUE);
JLabel nameField = new JLabel();
// nameField.setText("입력된 고객 이름");
nameField.setText(UserInIt.getmUser().getName());
nameField.setFont(ft);
namePanel.add(nameLabel);
namePanel.add(nameField);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 150, 1000, 100);
add(phonePanel);
JLabel phoneLabel = new JLabel("연락처 : ");
phoneLabel.setFont(ft);
JLabel phoneField = new JLabel();
// phoneField.setText("입력된 고객 연락처");
phoneField.setText(String.valueOf(UserInIt.getmUser().getPhone()));
phoneField.setFont(ft);
phonePanel.add(phoneLabel);
phonePanel.add(phoneField);
}
}
- CartAddItemPage 클래스 수정
package com.market.page;
import javax.swing.*;
import com.market.bookitem.Book;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class CartAddItemPage extends JPanel {
ImageIcon imageBook;
int mSelectRow = 0;
Cart mCart;
public CartAddItemPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
mCart = cart;
// 도서 이밎 표시를 위한 패널 영역 설정 및 출력
JPanel imagePanel = new JPanel();
imagePanel.setBounds(20, 0, 300, 400);
imageBook = new ImageIcon("src/images/ISBN1234.jpg");
imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
JLabel label = new JLabel(imageBook);
imagePanel.add(label);
add(imagePanel);
// 도서 목록 테이블 표시를 위한 패널 영역 설정 및 출력
JPanel tablePanel = new JPanel();
tablePanel.setBounds(300, 0, 700, 400);
add(tablePanel);
ArrayList<Book> booklist = BookInIt.getmBookList();
Object[] tableHeader = { "도서ID", "도서명", "가격", "저자", "설명", "분야", "출판일" };
Object[][] content = new Object[booklist.size()][tableHeader.length];
for (int i = 0; i < booklist.size(); i++) {
Book bookitem = booklist.get(i);
content[i][0] = bookitem.getBookId();
content[i][1] = bookitem.getName();
content[i][2] = bookitem.getUnitPrice();
content[i][3] = bookitem.getAuthor();
content[i][4] = bookitem.getDescription();
content[i][5] = bookitem.getCategory();
content[i][6] = bookitem.getReleaseDate();
}
JTable bookTable = new JTable(content, tableHeader);
bookTable.setRowSelectionInterval(0, 0);
bookTable.getSelectedColumn();
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(600, 350));
jScrollPane.setViewportView(bookTable);
tablePanel.add(jScrollPane);
// <장바구니에 담기> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 400, 1000, 400);
add(buttonPanel);
JLabel buttonLabel = new JLabel("장바구니에 담기");
buttonLabel.setFont(ft);
JButton addButton = new JButton();
addButton.add(buttonLabel);
buttonPanel.add(addButton);
bookTable.addMouseListener(new MouseListener() { // 도서 목록 테이블의 행 선택에 대한 마우스 이벤트 처리
public void mouseClicked(MouseEvent e) { // 마우스 클릭 이벤트 처리
int row = bookTable.getSelectedRow();
int col = bookTable.getSelectedColumn();
mSelectRow = row;
Object value = bookTable.getValueAt(row, 0);
String str = value + ".jpg";
imageBook = new ImageIcon("./images/" + str);
imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
JLabel label = new JLabel(imageBook);
imagePanel.removeAll();
imagePanel.add(label);
imagePanel.revalidate();
imagePanel.repaint();
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
addButton.addActionListener(new ActionListener() { // 장바구니 담기 버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
ArrayList<Book> booklist = BookInIt.getmBookList();
int select = JOptionPane.showConfirmDialog(addButton, "장바구니에 추가하겠습니까?");
if (select == 0) {
int numId = mSelectRow;
if (!isCartInBook(booklist.get(numId).getBookId())) {
mCart.insertBook(booklist.get(numId));
}
JOptionPane.showMessageDialog(addButton, "추가했습니다");
}
}
});
}
public boolean isCartInBook(String bookId) {
return mCart.isCartInBook(bookId);
}
}
- CartItemListPage 클래스 수정
package com.market.page;
import javax.swing.*;
import com.market.cart.Cart;
import com.market.cart.CartItem;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class CartItemListPage extends JPanel {
JTable cartTable;
Object[] tableHeader = { "도서ID", "도서명", "단가", "수량", "총가격" };
Cart mCart = new Cart();
public static int mSelectRow = -1;
public CartItemListPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
this.mCart = cart;
this.setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
this.setPreferredSize(rect.getSize());
// 도서가 담긴 장바구니의 테이블 표시를 위한 패널 영역 설정 및 출력
JPanel bookPanel = new JPanel();
bookPanel.setBounds(0, 0, 1000, 400);
add(bookPanel);
ArrayList<CartItem> cartItem = mCart.getmCartItem();
Object[][] content = new Object[cartItem.size()][tableHeader.length];
Integer totalPrice = 0;
for (int i = 0; i < cartItem.size(); i++) {
CartItem item = cartItem.get(i);
content[i][0] = item.getBookID();
content[i][1] = item.getItemBook().getName();
content[i][2] = item.getItemBook().getUnitPrice();
content[i][3] = item.getQuantity();
content[i][4] = item.getTotalPrice();
totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
}
cartTable = new JTable(content, tableHeader);
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(600, 350));
jScrollPane.setViewportView(cartTable);
bookPanel.add(jScrollPane);
// 총 금액 표시를 위한 패널 영역 설정 및 출력
JPanel totalPricePanel = new JPanel();
totalPricePanel.setBounds(0, 400, 1000, 50);
// totalPricePanel.setBackground(Color.RED);
JLabel totalPricelabel = new JLabel("총금액: " + totalPrice + " 원");
totalPricelabel.setForeground(Color.red);
totalPricelabel.setFont(ft);
totalPricePanel.add(totalPricelabel);
add(totalPricePanel);
// <장바구니 비우기>, <장바구니의 항목 삭제하기>, <장바구니 새로 고침> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBounds(0, 450, 1000, 50);
add(buttonPanel);
JLabel buttonLabel = new JLabel("장바구니 비우기");
buttonLabel.setFont(ft);
JButton clearButton = new JButton();
clearButton.add(buttonLabel);
buttonPanel.add(clearButton);
clearButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ArrayList<CartItem> cartItem = cart.getmCartItem();
if (cart.mCartCount == 0)
JOptionPane.showMessageDialog(clearButton, "장바구니에 항목이 없습니다");
else {
int select = JOptionPane.showConfirmDialog(clearButton, "장바구니의 모든 항목을 삭제하겠습니까? ");
if (select == 0) {
TableModel tableModel = new DefaultTableModel(new Object[0][0], tableHeader);
cartTable.setModel(tableModel);
totalPricelabel.setText("총금액: " + 0 + " 원");
JOptionPane.showMessageDialog(clearButton, "장바구니의 모든 항목을 삭제했습니다");
cart.deleteBook();
}
}
}
});
JLabel removeLabel = new JLabel("장바구니의 항목 삭제하기");
removeLabel.setFont(ft);
JButton removeButton = new JButton();
removeButton.add(removeLabel);
buttonPanel.add(removeButton);
removeButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (cart.mCartCount == 0)
JOptionPane.showMessageDialog(clearButton, "장바구니에 항목이 없습니다");
else if (mSelectRow == -1)
JOptionPane.showMessageDialog(clearButton, "장바구니에서 삭제할 항목을 선택하세요");
else {
ArrayList<CartItem> cartItem = cart.getmCartItem();
cartItem.remove(mSelectRow);
cart.mCartCount -= 1;
Object[][] content = new Object[cartItem.size()][tableHeader.length];
Integer totalPrice = 0;
for (int i = 0; i < cartItem.size(); i++) {
CartItem item = cartItem.get(i);
content[i][0] = item.getBookID();
content[i][1] = item.getItemBook().getName();
content[i][2] = item.getItemBook().getUnitPrice();
content[i][3] = item.getQuantity();
content[i][4] = item.getTotalPrice();
totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
}
TableModel tableModel = new DefaultTableModel(content, tableHeader);
totalPricelabel.setText("총금액: " + totalPrice + " 원");
cartTable.setModel(tableModel);
mSelectRow = -1;
}
}
});
cartTable.addMouseListener(new MouseListener() { // 장바구니 테이블의 행 선택에 대한 이벤트 처리
public void mouseClicked(MouseEvent e) {
int row = cartTable.getSelectedRow();
mSelectRow = row;
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
JLabel refreshLabel = new JLabel("장바구니 새로 고침");
refreshLabel.setFont(ft);
JButton refreshButton = new JButton();
refreshButton.add(refreshLabel);
buttonPanel.add(refreshButton);
refreshButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ArrayList<CartItem> cartItem = cart.getmCartItem();
Object[][] content = new Object[cartItem.size()][tableHeader.length];
Integer totalPrice = 0;
for (int i = 0; i < cartItem.size(); i++) {
CartItem item = cartItem.get(i);
content[i][0] = item.getBookID();
content[i][1] = item.getItemBook().getName();
content[i][2] = item.getItemBook().getUnitPrice();
content[i][3] = item.getQuantity();
content[i][4] = item.getTotalPrice();
totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
}
TableModel tableModel = new DefaultTableModel(content, tableHeader);
totalPricelabel.setText("총금액: " + totalPrice + " 원");
cartTable.setModel(tableModel);
}
});
}
}
- CartShippingPage 클래스 수정
package com.market.page;
import javax.swing.*;
import java.awt.*;
import com.market.cart.Cart;
import com.market.member.UserInIt;
import java.awt.event.ActionEvent;
public class CartShippingPage extends JPanel {
Cart mCart;
JPanel shippingPanel;
JPanel radioPanel;
public CartShippingPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
// 고객 정보 라디오버튼 선택 표시를 위한 패널 영역 설정 및 출력
radioPanel = new JPanel();
radioPanel.setBounds(300, 0, 700, 50);
radioPanel.setLayout(new FlowLayout());
add(radioPanel);
JLabel radioLabel = new JLabel("배송받을 분은 고객정보와 같습니까?");
radioLabel.setFont(ft);
JRadioButton radioOk = new JRadioButton("예");
radioOk.setFont(ft);
JRadioButton radioNo = new JRadioButton("아니오");
radioNo.setFont(ft);
radioPanel.add(radioLabel);
radioPanel.add(radioOk);
radioPanel.add(radioNo);
// 배송지 입력, 영수증 표시를 위한 패널 영역 설정 및 출력
shippingPanel = new JPanel();
shippingPanel.setBounds(200, 50, 700, 500);
shippingPanel.setLayout(null);
add(shippingPanel);
radioOk.setSelected(true);
radioNo.setSelected(false);
UserShippingInfo(true);
this.mCart = cart;
radioOk.addActionListener(new AbstractAction() { // 예 라디오버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
if (radioOk.isSelected()) {
shippingPanel.removeAll();
UserShippingInfo(true);
shippingPanel.revalidate();
shippingPanel.repaint();
radioNo.setSelected(false);
}
}
});
radioNo.addActionListener(new AbstractAction() { // 아니요 라디오버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
if (radioNo.isSelected()) {
shippingPanel.removeAll();
UserShippingInfo(false);
shippingPanel.revalidate();
shippingPanel.repaint();
radioOk.setSelected(false);
}
}
});
}
public void UserShippingInfo(boolean select) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
// 고객명 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 100, 700, 50);
// namePanel.setBackground(Color.GRAY);
JLabel nameLabel = new JLabel("고객명 : ");
nameLabel.setFont(ft);
namePanel.add(nameLabel);
JTextField nameLabel2 = new JTextField(15);
nameLabel2.setFont(ft);
if (select) {
nameLabel2.setBackground(Color.LIGHT_GRAY);
// nameLabel2.setText("입력된 고객 이름");
nameLabel2.setText(UserInIt.getmUser().getName());
}
namePanel.add(nameLabel2);
shippingPanel.add(namePanel);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 150, 700, 50);
JLabel phoneLabel = new JLabel("연락처 : ");
phoneLabel.setFont(ft);
phonePanel.add(phoneLabel);
JTextField phoneLabel2 = new JTextField(15);
phoneLabel2.setFont(ft);
if (select) {
phoneLabel2.setBackground(Color.LIGHT_GRAY);
// phoneLabel2.setText("입력된 고객 연락처");
phoneLabel2.setText(String.valueOf(UserInIt.getmUser().getPhone()));
}
phonePanel.add(phoneLabel2);
shippingPanel.add(phonePanel);
// 배송지 표시를 위한 패널 영역 설정 및 출력
JPanel addressPanel = new JPanel();
addressPanel.setBounds(0, 200, 700, 50);
JLabel label = new JLabel("배송지 : ");
label.setFont(ft);
addressPanel.add(label);
JTextField addressText = new JTextField(15);
addressText.setFont(ft);
addressPanel.add(addressText);
shippingPanel.add(addressPanel);
// <주문 완려> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 300, 700, 100);
JLabel buttonLabel = new JLabel("주문 완료");
buttonLabel.setFont(new Font("함초롬돋움", Font.BOLD, 15));
JButton orderButton = new JButton();
orderButton.add(buttonLabel);
buttonPanel.add(orderButton);
shippingPanel.add(buttonPanel);
orderButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
radioPanel.removeAll();
radioPanel.revalidate();
radioPanel.repaint();
shippingPanel.removeAll();
shippingPanel.add("주문 배송지", new CartOrderBillPage(shippingPanel, mCart));
mCart.deleteBook();
shippingPanel.revalidate();
shippingPanel.repaint();
}
});
}
}
- CartOrderBillPage 클래스 수정
package com.market.page;
import javax.swing.*;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import com.market.member.UserInIt;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CartOrderBillPage extends JPanel {
Cart mCart;
JPanel shippingPanel;
JPanel radioPanel;
public CartOrderBillPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
this.mCart = cart;
// 주문 내용 결과 표시를 위한 패널 영역 설정 및 출력
shippingPanel = new JPanel();
// shippingPanel.setBounds(200, 50, 700, 500);
shippingPanel.setBounds(0, 0, 700, 500);
shippingPanel.setLayout(null);
// add(shippingPanel);
panel.add(shippingPanel);
// printBillInfo("입력된 고객 이름", "입력된 고객 연락처", "입력된 고객 배송지");
printBillInfo(UserInIt.getmUser().getName(), String.valueOf(UserInIt.getmUser().getPhone()), UserInIt.getmUser().getAddress());
}
public void printBillInfo(String name, String phone, String address) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
// -배송받을 고객 정보 표시를 위한 패널 영역 설정 및 출력
JPanel panel01 = new JPanel();
panel01.setBounds(0, 0, 500, 30);
// panel01.setBackground(Color.GRAY);
JLabel label01 = new JLabel("---------------------배송받을 고객 정보-----------------------");
label01.setFont(ft);
panel01.add(label01);
shippingPanel.add(panel01);
// 고객명, 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel panel02 = new JPanel();
panel02.setBounds(0, 30, 500, 30);
JLabel label02 = new JLabel("고객명 : " + name + " 연락처 : " + phone);
label02.setHorizontalAlignment(JLabel.LEFT);
label02.setFont(ft);
panel02.add(label02);
shippingPanel.add(panel02);
// 배송지, 발송일 표시를 위한 패녈 영역 설정 및 출력
JPanel panel03 = new JPanel();
panel03.setBounds(0, 60, 500, 30);
JLabel label03 = new JLabel("배송지 : " + address + " 발송일 : " + strDate);
label03.setHorizontalAlignment(JLabel.LEFT);
label03.setFont(ft);
panel03.add(label03);
shippingPanel.add(panel03);
// 주문 도서 목록 표시를 위한 패널 영역 설정 및 출력
JPanel printPanel = new JPanel();
printPanel.setBounds(0, 100, 500, 300);
printCart(printPanel);
shippingPanel.add(printPanel);
}
public void printCart(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 12);
// 장바구니 상품 목록 표시를 위한 패널 영역 설정 및 출력
JPanel panel01 = new JPanel();
panel01.setBounds(0, 0, 500, 5);
JLabel label01 = new JLabel(" 장바구니 상품 목록 :");
label01.setFont(ft);
panel01.add(label01);
panel.add(panel01);
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel02 = new JPanel();
panel02.setBounds(0, 20, 500, 5);
JLabel label02 = new JLabel("------------------------------------");
label02.setFont(ft);
panel02.add(label02);
panel.add(panel02);
// 타이틀 표시를 위한 패널 영역 설정 및 출력
JPanel panel03 = new JPanel();
panel03.setBounds(0, 25, 500, 5);
JLabel label03 = new JLabel(" 도서ID | 수량 | 합계 ");
label03.setFont(ft);
panel03.add(label03);
panel.add(panel03);
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel04 = new JPanel();
panel04.setBounds(0, 30, 500, 5);
JLabel label04 = new JLabel("--------------------------------------");
label04.setFont(ft);
panel04.add(label04);
panel.add(panel04);
for (int i = 0; i < mCart.mCartItem.size(); i++) { // 13 // 장바구니 주문 결과 표시를 위한 패널 영역 설정 및 출력
JPanel panel05 = new JPanel();
panel05.setBounds(0, 35 + (i * 5), 500, 5);
JLabel label05 = new JLabel(" " + mCart.mCartItem.get(i).getBookID() + " "
+ mCart.mCartItem.get(i).getQuantity() + " "
+ mCart.mCartItem.get(i).getTotalPrice());
label05.setFont(ft);
panel05.add(label05);
panel.add(panel05);
}
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel06 = new JPanel();
panel06.setBounds(0, 35 + (mCart.mCartItem.size() * 5), 500, 5);
JLabel label06 = new JLabel("--------------------------------------");
label06.setFont(ft);
panel06.add(label06);
panel.add(panel06);
int sum = 0;
for (int i = 0; i < mCart.mCartCount; i++)
sum += mCart.mCartItem.get(i).getTotalPrice();
System.out.println("------------" + mCart.mCartCount);
// 주문 총금액 표시를 위한 패널 영역 설정 및 출력
JPanel panel07 = new JPanel();
panel07.setBounds(0, 40 + (mCart.mCartItem.size() * 5), 500, 5);
JLabel label07 = new JLabel(" 주문 총금액 : " + sum + "원");
// label04.setHorizontalAlignment(JLabel.CENTER);
label07.setFont(new Font("함초롬돋움", Font.BOLD, 15));
panel07.add(label07);
panel.add(panel07);
}
}
- AdminLoginDialog 클래스 생성
package com.market.page;
import com.market.member.Admin;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AdminLoginDialog extends JDialog {
JTextField pwField, idField;
public boolean isLogin = false;
public AdminLoginDialog(JFrame frame, String str) {
super(frame, "관리자로그인", true);
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - 400) / 2, (screenSize.height - 300) / 2);
setSize(400, 300);
setLayout(null);
// 관리자 로그인 표시를 위한 패널 영역 설정 및 출력
JPanel titlePanel = new JPanel();
titlePanel.setBounds(0, 20, 400, 50);
add(titlePanel);
JLabel titleLabel = new JLabel("관리자 로그인");
titleLabel.setFont(new Font("함초롬돋움", Font.BOLD, 20));
titlePanel.add(titleLabel);
// 아이디 표시를 위한 패널 영역 설정 및 출력
JPanel idPanel = new JPanel();
idPanel.setBounds(0, 70, 400, 50);
add(idPanel);
JLabel idLabel = new JLabel("아 이 디 : ");
idLabel.setFont(ft);
idField = new JTextField(10);
idField.setFont(ft);
idPanel.add(idLabel);
idPanel.add(idField);
// 비밀번호 표시를 위한 패널 영역 설정 및 출력
JPanel pwPanel = new JPanel();
pwPanel.setBounds(0, 120, 400, 50);
add(pwPanel);
JLabel pwLabel = new JLabel("비밀번호 : ");
pwLabel.setFont(ft);
pwField = new JTextField(10);
pwField.setFont(ft);
pwPanel.add(pwLabel);
pwPanel.add(pwField);
// 확인, 취소 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 170, 400, 50);
add(buttonPanel);
JLabel okLabel = new JLabel("확인");
okLabel.setFont(ft);
JButton okButton = new JButton();
okButton.add(okLabel);
buttonPanel.add(okButton);
JLabel cancelLabel = new JLabel("취소");
cancelLabel.setFont(ft);
JButton cancelBtn = new JButton();
cancelBtn.add(cancelLabel);
buttonPanel.add(cancelBtn);
okButton.addActionListener(new ActionListener() { // 확인 버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
Admin admin = new Admin("", -1);
System.out.println(pwField.getText() + idField.getText());
System.out.println(admin.getId() + admin.getPassword());
if (admin.getId().equals(idField.getText()) && admin.getPassword().equals(pwField.getText())) {
isLogin = true;
dispose();
} else
JOptionPane.showMessageDialog(okButton, "관리자 정보가 일치하지 않습니다");
}
});
cancelBtn.addActionListener(new ActionListener() { // 취소 버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
isLogin = false;
dispose();
}
});
}
}
- AdminPage 클래스 수정
package com.market.page;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.io.FileWriter;
public class AdminPage extends JPanel {
public AdminPage(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
String strDate = formatter.format(date);
// 도서 ID 표시를 위한 패널 영역 설정 및 출력
JPanel idPanel = new JPanel();
idPanel.setBounds(100, 0, 700, 50);
JLabel idLabel = new JLabel("도서ID : ");
idLabel.setFont(ft);
JLabel idTextField = new JLabel();
idTextField.setFont(ft);
idTextField.setPreferredSize(new Dimension(290, 50));
idTextField.setText("ISBN" + strDate);
idPanel.add(idLabel);
idPanel.add(idTextField);
add(idPanel);
// 도서명 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(100, 50, 700, 50);
JLabel nameLabel = new JLabel("도서명 : ");
nameLabel.setFont(ft);
JTextField nameTextField = new JTextField(20);
nameTextField.setFont(ft);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
add(namePanel);
// 가격 표시를 위한 패널 영역 설정 및 출력
JPanel pricePanel = new JPanel();
pricePanel.setBounds(100, 100, 700, 50);
JLabel priceLabel = new JLabel("가 격 : ");
priceLabel.setFont(ft);
JTextField priceTextField = new JTextField(20);
priceTextField.setFont(ft);
pricePanel.add(priceLabel);
pricePanel.add(priceTextField);
add(pricePanel);
// 저자 표시를 위한 패널 영역 설정 및 출력
JPanel authorPanel = new JPanel();
authorPanel.setBounds(100, 150, 700, 50);
JLabel authorLabel = new JLabel("저 자 : ");
authorLabel.setFont(ft);
JTextField authorTextField = new JTextField(20);
authorTextField.setFont(ft);
authorPanel.add(authorLabel);
authorPanel.add(authorTextField);
add(authorPanel);
// 설명 표시를 위한 패널 영역 설정 및 출력
JPanel descPanel = new JPanel();
descPanel.setBounds(100, 200, 700, 50);
JLabel descLabel = new JLabel("설 명 : ");
descLabel.setFont(ft);
JTextField descTextField = new JTextField(20);
descTextField.setFont(ft);
descPanel.add(descLabel);
descPanel.add(descTextField);
add(descPanel);
//분야 표시를 위한 패널 영역 설정 및 출력
JPanel categoryPanel = new JPanel();
categoryPanel.setBounds(100, 250, 700, 50);
JLabel categoryLabel = new JLabel("분 야 : ");
categoryLabel.setFont(ft);
JTextField categoryTextField = new JTextField(20);
categoryTextField.setFont(ft);
categoryPanel.add(categoryLabel);
categoryPanel.add(categoryTextField);
add(categoryPanel);
//출판일 표시를 위한 패널 영역 설정 및 출력
JPanel datePanel = new JPanel();
datePanel.setBounds(100, 300, 700, 50);
JLabel dateLabel = new JLabel("출판일 : ");
dateLabel.setFont(ft);
JTextField dateTextField = new JTextField(20);
dateTextField.setFont(ft);
datePanel.add(dateLabel);
datePanel.add(dateTextField);
add(datePanel);
//<추가>, <취소> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(100, 350, 700, 50);
add(buttonPanel);
JLabel okLabel = new JLabel("추가");
okLabel.setFont(ft);
JButton okButton = new JButton();
okButton.add(okLabel);
buttonPanel.add(okButton);
okButton.addActionListener(new AbstractAction() { // 추가 버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
String[] writeBook = new String[7];
writeBook[0] = idTextField.getText();
writeBook[1] = nameTextField.getText();
writeBook[2] = priceTextField.getText();
writeBook[3] = authorTextField.getText();
writeBook[4] = descTextField.getText();
writeBook[5] = categoryTextField.getText();
writeBook[6] = dateTextField.getText();
try {
FileWriter fw = new FileWriter("book.txt", true);
for (int i = 0; i < 7; i++)
fw.write(writeBook[i] + "\n");
fw.close();
JOptionPane.showMessageDialog(okButton, "새 도서 정보가 저장되었습니다");
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
String strDate = formatter.format(date);
idTextField.setText("ISBN" + strDate);
nameTextField.setText("");
priceTextField.setText("");
authorTextField.setText("");
descTextField.setText("");
categoryTextField.setText("");
dateTextField.setText("");
System.out.println("새 도서 정보가 저장되었습니다.");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
JLabel noLabel = new JLabel("취소");
noLabel.setFont(ft);
JButton noButton = new JButton();
noButton.add(noLabel);
buttonPanel.add(noButton);
noButton.addActionListener(new AbstractAction() { // 취소 버튼 클릭 이벤트 처리
public void actionPerformed(ActionEvent e) {
nameTextField.setText("");
priceTextField.setText("");
authorTextField.setText("");
descTextField.setText("");
categoryTextField.setText("");
dateTextField.setText("");
}
});
}
}
package com.market.member;
public class UserInIt {
private static User mUser;
public static void setmUser(User mUser) {
UserInIt.mUser = mUser;
}
public static void init(String name, int phone) {
mUser = new User(name, phone);
}
public static User getmUser() {
return mUser;
}
}
BookMarket 프로젝트의 com.market.bookitem 패키지 이동
- BookInIt 클래스 생성
package com.market.bookitem;
import java.io.*;
import java.util.ArrayList;
public class BookInIt {
private static ArrayList<Book> mBookList;
private static int mTotalBook = 0;
public static void init() {
mTotalBook = totalFileToBookList();
mBookList = new ArrayList<Book>();
setFileToBookList(mBookList);
}
public static int totalFileToBookList() { // 파일에서 도서의 개수를 얻는 메서드 // BookMarket 프로젝트의 Welcome 클래스 메서드
try {
FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성
String str;
int num = 0;
while ((str = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때 까지 반복
if (str.contains("ISBN")) // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서의 개수 num을 1 증가시킴
++num;
}
reader.close(); // BufferedReader 객체 종료
fr.close(); // FileReader 객체 종료
return num;
} catch (Exception e) {
System.out.println(e);
}
return 0;
}
public static void setFileToBookList(ArrayList<Book> booklist) { // 파일에서 도서 정보 목록을 읽어 저장하는 매서드 // BookMarket 프로젝트의 Welcome 클래스 메서드
try {
FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성
String str2;
String[] readBook = new String[7];
while ((str2 = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때까지 반복
if (str2.contains("ISBN")) { // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서 정보에 대해 한 행씩 읽어 지역변수 readBook에 저장
readBook[0] = str2;
readBook[1] = reader.readLine();
readBook[2] = reader.readLine();
readBook[3] = reader.readLine();
readBook[4] = reader.readLine();
readBook[5] = reader.readLine();
readBook[6] = reader.readLine();
}
Book bookitem = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]);
booklist.add(bookitem);
}
reader.close(); // BufferedReader 객체 종료
fr.close(); // FileReader 객체 종료
} catch (Exception e) {
System.out.println(e);
}
}
public static ArrayList<Book> getmBookList() { // 도서 목록 불러오는 메서드
return mBookList;
}
public static void setmBookList(ArrayList<Book> mBookList) { // 도서 목록 저장하는 메서드
BookInIt.mBookList = mBookList;
}
public static int getmTotalBook() { // 총 도서 수량 불러오는 메서드
return mTotalBook;
}
public static void setmTotalBook(int mTotalBook) { // 총 도서 수량 저장하는 메서드
BookInIt.mTotalBook = mTotalBook;
}
}
BookMarket 프로젝트의 com.market.cart 패키지 이동
- Cart.java 의 getter(), setter() 메서드 추가
package com.market.cart;
import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
public class Cart implements CartInterface { // CartInterface 인터페이스의 자식 클래스 Cart 생성
public ArrayList<CartItem> mCartItem = new ArrayList<CartItem>(); // mCartItem은 ArrayList 클래스를 이용하여 장바구니에 항목을 담는 객체 변수
public static int mCartCount = 0; // 장바구니에 담긴 항목의 총 개수를 저장하는 변수
public Cart() { // Cart 클래스의 기본 생성자
}
public ArrayList<CartItem> getmCartItem(){ // 장바구니의 도서 항목 불러오는 메서드
return mCartItem;
}
public void setmCartItem(ArrayList<CartItem> mCartItem) { // 장바구니의 도서 항목 저장하는 메서드
this.mCartItem = mCartItem;
}
public void printBookList(ArrayList<Book> booklist) { // Book[] booklist -> ArrayList<Book> 전체 도서 정보 목록 출력 구현
for (int i = 0; i < booklist.size(); i++) {
Book bookitem = booklist.get(i);
System.out.print(bookitem.getBookId() + " | ");
System.out.print(bookitem.getName() + " | ");
System.out.print(bookitem.getUnitPrice() + " | ");
System.out.print(bookitem.getAuthor() + " | ");
System.out.print(bookitem.getDescription() + " | ");
System.out.print(bookitem.getCategory() + " | ");
System.out.print(bookitem.getReleaseDate() + " | ");
System.out.println("");
}
}
public void insertBook(Book book) { // CartItem에 도서 정보를 등록하는 메서드 구현
CartItem bookitem = new CartItem(book);
mCartItem.add(bookitem);
mCartCount = mCartItem.size();
}
public void deleteBook() { // 장바구니의 모든 항목을 삭제하는 메서드 구현
mCartItem.clear();
mCartCount = 0;
}
public void printCart() {
System.out.println("장바구니 상품 목록 :");
System.out.println("-----------------------------------------------");
System.out.println(" 도서ID \t| 수 량 \t| 합 계");
for (int i = 0; i < mCartCount; i++) {
System.out.print(" " + mCartItem.get(i).getBookID() + "\t| ");
System.out.print(" " + mCartItem.get(i).getQuantity() + "\t| ");
System.out.print(" " + mCartItem.get(i).getTotalPrice());
System.out.println(" ");
}
System.out.println("-----------------------------------------------");
}
public boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드 구현
boolean flag = false;
for (int i = 0; i < mCartItem.size(); i++) {
if (bookId == mCartItem.get(i).getBookID()) {
mCartItem.get(i).setQuantity(mCartItem.get(i).getQuantity() + 1);
flag = true;
}
}
return flag;
}
public void removeCart(int numId) { // 장바구니 순번 numId의 항목을 삭제하는 메서드 구현
mCartItem.remove(numId);
mCartCount = mCartItem.size();
}
}
com.market.main 패키지 생성
- GuestWindow 클래스 생성
- MainWindow 클래스 생성
package com.market.main;
import javax.swing.*;
import java.awt.*;
public class GuestWindow extends JFrame {
public GuestWindow(String title, int x, int y, int width, int height) {
initContainer(title, x, y, width, height); // initContainer() 메서드 호출
setVisible(true); // 프레임 보이기 설정
setResizable(true); // 프레임 크기 조절 가능 설정
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
}
private void initContainer(String title, int x, int y, int width, int height) {
setTitle(title); // 프레임 제목 설정
setBounds(x, y, width, height); // 프레임 위치, 크기 설정
setLayout(null); // 프레임 레이아웃 미설정
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
// user.png 이미지 표시를 위한 패널 영역 설정 및 출력
JPanel userPanel = new JPanel();
userPanel.setBounds(0, 100, 1000, 256);
ImageIcon imageIcon = new ImageIcon("src/images/user.png"); // ./images/user.png 이미지 불러오지 못함
imageIcon.setImage(imageIcon.getImage().getScaledInstance(160, 160, Image.SCALE_SMOOTH));
JLabel userLabel = new JLabel(imageIcon);
userPanel.add(userLabel);
add(userPanel);
// -- 고객 정보를 입력하세요 -- 표시를 위한 패널 영역 설정 및 출력
JPanel titlePanel = new JPanel();
titlePanel.setBounds(0, 350, 1000, 50);
add(titlePanel);
JLabel titleLabel = new JLabel("-- 고객 정보를 입력하세요 --");
titleLabel.setFont(ft); // JLabel인 titleLabel 글꼴 설정
titleLabel.setForeground(Color.BLUE); // JLabel인 titleLabel 문자열 색상 설정
titlePanel.add(titleLabel);
// 이름 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 400, 1000, 50);
add(namePanel);
JLabel nameLabel = new JLabel("이 름 : ");
nameLabel.setFont(ft);
namePanel.add(nameLabel);
// 이름 표시를 위한 패널 영역 설정 및 출력
JTextField nameField = new JTextField(10);
nameField.setFont(ft);
namePanel.add(nameField);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 450, 1000, 50);
add(phonePanel);
JLabel phoneLabel = new JLabel("연락처 : ");
phonePanel.setFont(ft);
phonePanel.add(phoneLabel);
JTextField phoneField = new JTextField(10);
phonePanel.setFont(ft);
phonePanel.add(phoneField);
// <쇼핑하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 500, 1000, 100);
add(buttonPanel);
JLabel buttonLabel = new JLabel("쇼핑하기", new ImageIcon("src/images/shop.png"), JLabel.LEFT); // images/shop.png 이미지 불러오지 못함
buttonLabel.setFont(ft);
JButton enterButton = new JButton();
enterButton.add(buttonLabel);
buttonPanel.add(enterButton);
}
// public static void main(String[] args) {
// new GuestWindow("고객 정보 입력", 0, 0, 1000, 750); // 테스트 화면 창을 띄우기 위한 실행용 메서드
// }
}
package com.market.main;
import javax.swing.*;
import java.awt.*;
public class MainWindow extends JFrame {
static JPanel mMenuPanel, mPagePanel;
public MainWindow(String title, int x, int y, int width, int height) {
initContainer(title, x, y, width, height); // initContainer() 메서드 호출
setVisible(true); // 프레임 보이기 설정
setResizable(true); // 프레임 크기 조절 가능 설정
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
}
private void initContainer(String title, int x, int y, int width, int height) {
setTitle(title); // 프레임 제목 설정
setBounds(x, y, width, height); // 프레임 위치, 크기 설정
setLayout(null); // 프레임 레이아웃 미설정
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
//메뉴 버튼 표시를 위한 프레임 상단의 패널 영역 설정 및 출력
mMenuPanel = new JPanel();
mMenuPanel.setBounds(0, 20, width, 130);
menuIntroduction();
add(mMenuPanel);
// 메뉴 버튼별 클릭 시 페이지 표시를 위한 프레임 하단의 패널 영역 설정 및 출력
mPagePanel = new JPanel();
mPagePanel.setBounds(0, 150, width, height);
add(mPagePanel);
}
private void menuIntroduction() {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
// <고객 정보 확인하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt1 = new JButton("고객 정보 확인하기", new ImageIcon("src/images/1.png"));
bt1.setBounds(0, 0, 100, 50);
bt1.setFont(ft);
mMenuPanel.add(bt1);
// <장바구니 상품 목록보기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt2 = new JButton("장바구니 상품 목록보기", new ImageIcon("src/images/2.png"));
bt2.setBounds(0, 0, 100, 30);
bt2.setFont(ft);
mMenuPanel.add(bt2);
// <장바구니 비우기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt3 = new JButton("장바구니 비우기", new ImageIcon("src/images/3.png"));
bt3.setBounds(0, 0, 100, 30);
bt3.setFont(ft);
mMenuPanel.add(bt3);
// <장바구니에 항목 추가하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt4 = new JButton("장바구니에 항목 추가하기", new ImageIcon("src/images/4.png"));
bt4.setFont(ft);
mMenuPanel.add(bt4);
// <장바구니의 항목 수량 줄이기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt5 = new JButton("장바구니의 항목 수량 줄이기", new ImageIcon("src/images/5.png"));
bt5.setFont(ft);
mMenuPanel.add(bt5);
// <장바구니의 항목 삭제하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt6 = new JButton("장바구니의 항목 삭제하기", new ImageIcon("src/images/6.png"));
bt6.setFont(ft);
mMenuPanel.add(bt6);
// <주문하기> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt7 = new JButton("주문하기", new ImageIcon("src/images/7.png"));
bt7.setFont(ft);
mMenuPanel.add(bt7);
// <종료> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt8 = new JButton("종료", new ImageIcon("src/images/8.png"));
bt8.setFont(ft);
mMenuPanel.add(bt8);
// <관리자> 버튼 표시를 위한 패널 영역 설정 및 출력
JButton bt9 = new JButton("관리자", new ImageIcon("src/images/9.png"));
bt9.setFont(ft);
mMenuPanel.add(bt9);
}
// public static void main(String[] args) {
// new MainWindow("도서 쇼핑몰", 0, 0, 1000, 750); // 테스트 화면 창을 띄우기 위한 실행용 메서드
// }
}
com.market.page 패키지 생성
- GuestInfoPage, CartAddItemPage, CartItemListPage, CartShippingPage, CartOrderBillPage, AdminPage 클래스 생성
package com.market.page;
import javax.swing.*;
import java.awt.*;
public class GuestInfoPage extends JPanel {
public GuestInfoPage(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
// 이름 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 100, 1000, 50);
add(namePanel);
JLabel nameLabel = new JLabel("이 름 : ");
nameLabel.setFont(ft);
nameLabel.setBackground(Color.BLUE);
JLabel nameField = new JLabel();
nameField.setText("입력된 고객 이름");
nameField.setFont(ft);
namePanel.add(nameLabel);
namePanel.add(nameField);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 150, 1000, 100);
add(phonePanel);
JLabel phoneLabel = new JLabel("연락처 : ");
phoneLabel.setFont(ft);
JLabel phoneField = new JLabel();
phoneField.setText("입력된 고객 연락처");
phoneField.setFont(ft);
phonePanel.add(phoneLabel);
phonePanel.add(phoneField);
}
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
//
// frame.add(mPagePanel);
// mPagePanel.add("고객 정보 확인하기", new GuestInfoPage(mPagePanel));
// frame.setVisible(true);
// }
}
package com.market.page;
import javax.swing.*;
import com.market.bookitem.Book;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.util.ArrayList;
public class CartAddItemPage extends JPanel {
ImageIcon imageBook;
int mSelectRow = 0;
Cart mCart;
public CartAddItemPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
mCart = cart;
// 도서 이밎 표시를 위한 패널 영역 설정 및 출력
JPanel imagePanel = new JPanel();
imagePanel.setBounds(20, 0, 300, 400);
imageBook = new ImageIcon("src/images/ISBN1234.jpg");
imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
JLabel label = new JLabel(imageBook);
imagePanel.add(label);
add(imagePanel);
// 도서 목록 테이블 표시를 위한 패널 영역 설정 및 출력
JPanel tablePanel = new JPanel();
tablePanel.setBounds(300, 0, 700, 400);
add(tablePanel);
ArrayList<Book> booklist = BookInIt.getmBookList();
Object[] tableHeader = { "도서ID", "도서명", "가격", "저자", "설명", "분야", "출판일" };
Object[][] content = new Object[booklist.size()][tableHeader.length];
for (int i = 0; i < booklist.size(); i++) {
Book bookitem = booklist.get(i);
content[i][0] = bookitem.getBookId();
content[i][1] = bookitem.getName();
content[i][2] = bookitem.getUnitPrice();
content[i][3] = bookitem.getAuthor();
content[i][4] = bookitem.getDescription();
content[i][5] = bookitem.getCategory();
content[i][6] = bookitem.getReleaseDate();
}
JTable bookTable = new JTable(content, tableHeader);
bookTable.setRowSelectionInterval(0, 0);
bookTable.getSelectedColumn();
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(600, 350));
jScrollPane.setViewportView(bookTable);
tablePanel.add(jScrollPane);
// <장바구니에 담기> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 400, 1000, 400);
add(buttonPanel);
JLabel buttonLabel = new JLabel("장바구니에 담기");
buttonLabel.setFont(ft);
JButton addButton = new JButton();
addButton.add(buttonLabel);
buttonPanel.add(addButton);
}
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
// Cart mCart = new Cart();
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
// frame.add(mPagePanel);
//
// BookInIt.init();
// mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
// frame.setVisible(true);
// }
}
package com.market.page;
import javax.swing.*;
import com.market.cart.Cart;
import com.market.cart.CartItem;
import java.awt.*;
import java.util.ArrayList;
public class CartItemListPage extends JPanel {
JTable cartTable;
Object[] tableHeader = { "도서ID", "도서명", "단가", "수량", "총가격" };
Cart mCart = new Cart();
public static int mSelectRow = -1;
public CartItemListPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
this.mCart = cart;
this.setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
this.setPreferredSize(rect.getSize());
// 도서가 담긴 장바구니의 테이블 표시를 위한 패널 영역 설정 및 출력
JPanel bookPanel = new JPanel();
bookPanel.setBounds(0, 0, 1000, 400);
add(bookPanel);
ArrayList<CartItem> cartItem = mCart.getmCartItem();
Object[][] content = new Object[cartItem.size()][tableHeader.length];
Integer totalPrice = 0;
for (int i = 0; i < cartItem.size(); i++) {
CartItem item = cartItem.get(i);
content[i][0] = item.getBookID();
content[i][1] = item.getItemBook().getName();
content[i][2] = item.getItemBook().getUnitPrice();
content[i][3] = item.getQuantity();
content[i][4] = item.getTotalPrice();
totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
}
cartTable = new JTable(content, tableHeader);
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(600, 350));
jScrollPane.setViewportView(cartTable);
bookPanel.add(jScrollPane);
// 총 금액 표시를 위한 패널 영역 설정 및 출력
JPanel totalPricePanel = new JPanel();
totalPricePanel.setBounds(0, 400, 1000, 50);
// totalPricePanel.setBackground(Color.RED);
JLabel totalPricelabel = new JLabel("총금액: " + totalPrice + " 원");
totalPricelabel.setForeground(Color.red);
totalPricelabel.setFont(ft);
totalPricePanel.add(totalPricelabel);
add(totalPricePanel);
// <장바구니 비우기>, <장바구니의 항목 삭제하기>, <장바구니 새로 고침> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBounds(0, 450, 1000, 50);
add(buttonPanel);
JLabel buttonLabel = new JLabel("장바구니 비우기");
buttonLabel.setFont(ft);
JButton clearButton = new JButton();
clearButton.add(buttonLabel);
buttonPanel.add(clearButton);
JLabel removeLabel = new JLabel("장바구니의 항목 삭제하기");
removeLabel.setFont(ft);
JButton removeButton = new JButton();
removeButton.add(removeLabel);
buttonPanel.add(removeButton);
JLabel refreshLabel = new JLabel("장바구니 새로 고침");
refreshLabel.setFont(ft);
JButton refreshButton = new JButton();
refreshButton.add(refreshLabel);
buttonPanel.add(refreshButton);
}
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
//
// Cart mCart = new Cart();
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
//
// frame.add(mPagePanel);
// mPagePanel.add("장바구니의 상품 목록 보기", new CartItemListPage(mPagePanel, mCart));
// frame.setVisible(true);
// }
}
package com.market.page;
import javax.swing.*;
import java.awt.*;
public class CartShippingPage extends JPanel {
JPanel shippingPanel;
JPanel radioPanel;
public CartShippingPage(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
// 고객 정보 라디오버튼 선택 표시를 위한 패널 영역 설정 및 출력
radioPanel = new JPanel();
radioPanel.setBounds(300, 0, 700, 50);
radioPanel.setLayout(new FlowLayout());
add(radioPanel);
JLabel radioLabel = new JLabel("배송받을 분은 고객 정보와 같습니까?");
radioLabel.setFont(ft);
JRadioButton radioOk = new JRadioButton("예");
radioOk.setFont(ft);
JRadioButton radioNo = new JRadioButton("아니요");
radioNo.setFont(ft);
radioPanel.add(radioLabel);
radioPanel.add(radioOk);
radioPanel.add(radioNo);
// 배송지 입력, 영수증 표시를 위한 패널 영역 설정 및 출력
shippingPanel = new JPanel();
shippingPanel.setBounds(200, 50, 700, 500);
shippingPanel.setLayout(null);
add(shippingPanel);
radioOk.setSelected(true);
radioNo.setSelected(false);
UserShippingInfo(true);
}
public void UserShippingInfo(boolean select) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
// 고객명 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(0, 100, 700, 50);
// namePanel.setBackground(Color.GRAY);
JLabel nameLabel = new JLabel("고객명 : ");
nameLabel.setFont(ft);
namePanel.add(nameLabel);
JTextField nameLabel2 = new JTextField(15);
nameLabel2.setFont(ft);
if (select) {
nameLabel2.setBackground(Color.LIGHT_GRAY);
nameLabel2.setText("입력된 고객 이름");
}
namePanel.add(nameLabel2);
shippingPanel.add(namePanel);
// 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel phonePanel = new JPanel();
phonePanel.setBounds(0, 150, 700, 50);
JLabel phoneLabel = new JLabel("연락처 : ");
phoneLabel.setFont(ft);
phonePanel.add(phoneLabel);
JTextField phoneLabel2 = new JTextField(15);
phoneLabel2.setFont(ft);
if (select) {
phoneLabel2.setBackground(Color.LIGHT_GRAY);
phoneLabel2.setText("입력된 고객 연락처");
}
phonePanel.add(phoneLabel2);
shippingPanel.add(phonePanel);
// 배송지 표시를 위한 패널 영역 설정 및 출력
JPanel addressPanel = new JPanel();
addressPanel.setBounds(0, 200, 700, 50);
JLabel label = new JLabel("배송지 : ");
label.setFont(ft);
addressPanel.add(label);
JTextField addressText = new JTextField(15);
addressText.setFont(ft);
addressPanel.add(addressText);
shippingPanel.add(addressPanel);
// <주문 완려> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(0, 300, 700, 100);
JLabel buttonLabel = new JLabel("주문 완료");
buttonLabel.setFont(new Font("함초롬돋움", Font.BOLD, 15));
JButton orderButton = new JButton();
orderButton.add(buttonLabel);
buttonPanel.add(orderButton);
shippingPanel.add(buttonPanel);
}
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
//
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
//
// frame.add(mPagePanel);
// mPagePanel.add("주문 배송지", new CartShippingPage(mPagePanel));
// frame.setVisible(true);
//
// }
}
package com.market.page;
import javax.swing.*;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CartOrderBillPage extends JPanel {
Cart mCart;
JPanel shippingPanel;
JPanel radioPanel;
public CartOrderBillPage(JPanel panel, Cart cart) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15);
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
this.mCart = cart;
// 주문 내용 결과 표시를 위한 패널 영역 설정 및 출력
shippingPanel = new JPanel();
shippingPanel.setBounds(200, 50, 700, 500);
shippingPanel.setLayout(null);
add(shippingPanel);
printBillInfo("입력된 고객 이름", "입력된 고객 연락처", "입력된 고객 배송지");
}
public void printBillInfo(String name, String phone, String address) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
// -배송받을 고객 정보 표시를 위한 패널 영역 설정 및 출력
JPanel panel01 = new JPanel();
panel01.setBounds(0, 0, 500, 30);
// panel01.setBackground(Color.GRAY);
JLabel label01 = new JLabel("---------------------배송받을 고객 정보-----------------------");
label01.setFont(ft);
panel01.add(label01);
shippingPanel.add(panel01);
// 고객명, 연락처 표시를 위한 패널 영역 설정 및 출력
JPanel panel02 = new JPanel();
panel02.setBounds(0, 30, 500, 30);
JLabel label02 = new JLabel("고객명 : " + name + " 연락처 : " + phone);
label02.setHorizontalAlignment(JLabel.LEFT);
label02.setFont(ft);
panel02.add(label02);
shippingPanel.add(panel02);
// 배송지, 발송일 표시를 위한 패녈 영역 설정 및 출력
JPanel panel03 = new JPanel();
panel03.setBounds(0, 60, 500, 30);
JLabel label03 = new JLabel("배송지 : " + address + " 발송일 : " + strDate);
label03.setHorizontalAlignment(JLabel.LEFT);
label03.setFont(ft);
panel03.add(label03);
shippingPanel.add(panel03);
// 주문 도서 목록 표시를 위한 패널 영역 설정 및 출력
JPanel printPanel = new JPanel();
printPanel.setBounds(0, 100, 500, 300);
printCart(printPanel);
shippingPanel.add(printPanel);
}
public void printCart(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 12);
// 장바구니 상품 목록 표시를 위한 패널 영역 설정 및 출력
JPanel panel01 = new JPanel();
panel01.setBounds(0, 0, 500, 5);
JLabel label01 = new JLabel(" 장바구니 상품 목록 :");
label01.setFont(ft);
panel01.add(label01);
panel.add(panel01);
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel02 = new JPanel();
panel02.setBounds(0, 20, 500, 5);
JLabel label02 = new JLabel("------------------------------------");
label02.setFont(ft);
panel02.add(label02);
panel.add(panel02);
// 타이틀 표시를 위한 패널 영역 설정 및 출력
JPanel panel03 = new JPanel();
panel03.setBounds(0, 25, 500, 5);
JLabel label03 = new JLabel(" 도서ID | 수량 | 합계 ");
label03.setFont(ft);
panel03.add(label03);
panel.add(panel03);
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel04 = new JPanel();
panel04.setBounds(0, 30, 500, 5);
JLabel label04 = new JLabel("--------------------------------------");
label04.setFont(ft);
panel04.add(label04);
panel.add(panel04);
for (int i = 0; i < mCart.mCartItem.size(); i++) { // 13 // 장바구니 주문 결과 표시를 위한 패널 영역 설정 및 출력
JPanel panel05 = new JPanel();
panel05.setBounds(0, 35 + (i * 5), 500, 5);
JLabel label05 = new JLabel(" " + mCart.mCartItem.get(i).getBookID() + " "
+ mCart.mCartItem.get(i).getQuantity() + " "
+ mCart.mCartItem.get(i).getTotalPrice());
label05.setFont(ft);
panel05.add(label05);
panel.add(panel05);
}
// ---- 표시를 위한 패널 영역 설정 및 출력
JPanel panel06 = new JPanel();
panel06.setBounds(0, 35 + (mCart.mCartItem.size() * 5), 500, 5);
JLabel label06 = new JLabel("--------------------------------------");
label06.setFont(ft);
panel06.add(label06);
panel.add(panel06);
int sum = 0;
for (int i = 0; i < mCart.mCartCount; i++)
sum += mCart.mCartItem.get(i).getTotalPrice();
System.out.println("------------" + mCart.mCartCount);
// 주문 총금액 표시를 위한 패널 영역 설정 및 출력
JPanel panel07 = new JPanel();
panel07.setBounds(0, 40 + (mCart.mCartItem.size() * 5), 500, 5);
JLabel label07 = new JLabel(" 주문 총금액 : " + sum + "원");
// label04.setHorizontalAlignment(JLabel.CENTER);
label07.setFont(new Font("함초롬돋움", Font.BOLD, 15));
panel07.add(label07);
panel.add(panel07);
}
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
//
// Cart mCart = new Cart();
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
//
// frame.add(mPagePanel);
// BookInIt.init();
// mPagePanel.add("주문하기", new CartOrderBillPage(mPagePanel, mCart));
// frame.setVisible(true);
//
// }
}
package com.market.page;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AdminPage extends JPanel {
public AdminPage(JPanel panel) {
Font ft;
ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
setLayout(null);
Rectangle rect = panel.getBounds();
System.out.println(rect);
setPreferredSize(rect.getSize());
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
String strDate = formatter.format(date);
// 도서 ID 표시를 위한 패널 영역 설정 및 출력
JPanel idPanel = new JPanel();
idPanel.setBounds(100, 0, 700, 50);
JLabel idLabel = new JLabel("도서ID : ");
idLabel.setFont(ft);
JLabel idTextField = new JLabel();
idTextField.setFont(ft);
idTextField.setPreferredSize(new Dimension(290, 50));
idTextField.setText("ISBN" + strDate);
idPanel.add(idLabel);
idPanel.add(idTextField);
add(idPanel);
// 도서명 표시를 위한 패널 영역 설정 및 출력
JPanel namePanel = new JPanel();
namePanel.setBounds(100, 50, 700, 50);
JLabel nameLabel = new JLabel("도서명 : ");
nameLabel.setFont(ft);
JTextField nameTextField = new JTextField(20);
nameTextField.setFont(ft);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
add(namePanel);
// 가격 표시를 위한 패널 영역 설정 및 출력
JPanel pricePanel = new JPanel();
pricePanel.setBounds(100, 100, 700, 50);
JLabel priceLabel = new JLabel("가 격 : ");
priceLabel.setFont(ft);
JTextField priceTextField = new JTextField(20);
priceTextField.setFont(ft);
pricePanel.add(priceLabel);
pricePanel.add(priceTextField);
add(pricePanel);
// 저자 표시를 위한 패널 영역 설정 및 출력
JPanel authorPanel = new JPanel();
authorPanel.setBounds(100, 150, 700, 50);
JLabel authorLabel = new JLabel("저 자 : ");
authorLabel.setFont(ft);
JTextField authorTextField = new JTextField(20);
authorTextField.setFont(ft);
authorPanel.add(authorLabel);
authorPanel.add(authorTextField);
add(authorPanel);
// 설명 표시를 위한 패널 영역 설정 및 출력
JPanel descPanel = new JPanel();
descPanel.setBounds(100, 200, 700, 50);
JLabel descLabel = new JLabel("설 명 : ");
descLabel.setFont(ft);
JTextField descTextField = new JTextField(20);
descTextField.setFont(ft);
descPanel.add(descLabel);
descPanel.add(descTextField);
add(descPanel);
//분야 표시를 위한 패널 영역 설정 및 출력
JPanel categoryPanel = new JPanel();
categoryPanel.setBounds(100, 250, 700, 50);
JLabel categoryLabel = new JLabel("분 야 : ");
categoryLabel.setFont(ft);
JTextField categoryTextField = new JTextField(20);
categoryTextField.setFont(ft);
categoryPanel.add(categoryLabel);
categoryPanel.add(categoryTextField);
add(categoryPanel);
//출판일 표시를 위한 패널 영역 설정 및 출력
JPanel datePanel = new JPanel();
datePanel.setBounds(100, 300, 700, 50);
JLabel dateLabel = new JLabel("출판일 : ");
dateLabel.setFont(ft);
JTextField dateTextField = new JTextField(20);
dateTextField.setFont(ft);
datePanel.add(dateLabel);
datePanel.add(dateTextField);
add(datePanel);
//<추가>, <취소> 버튼 표시를 위한 패널 영역 설정 및 출력
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(100, 350, 700, 50);
add(buttonPanel);
JLabel okLabel = new JLabel("추가");
okLabel.setFont(ft);
JButton okButton = new JButton();
okButton.add(okLabel);
buttonPanel.add(okButton);
JLabel noLabel = new JLabel("취소");
noLabel.setFont(ft);
JButton noButton = new JButton();
noButton.add(noLabel);
buttonPanel.add(noButton);
}
//
// public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
//
// JFrame frame = new JFrame();
// frame.setBounds(0, 0, 1000, 750);
// frame.setLayout(null);
//
// JPanel mPagePanel = new JPanel();
// mPagePanel.setBounds(0, 150, 1000, 750);
//
// frame.add(mPagePanel);
// mPagePanel.add("주문하기", new AdminPage(mPagePanel));
// frame.setVisible(true);
// }
}
package com.market.cart;
import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
public interface CartInterface { // 장바구니 처리의 메서드를 정의하기 위한 인터페이스 생성
void printBookList(ArrayList<Book> p); // 전체 도서 정보 목록 출력
boolean isCartInBook(String id); /// 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
void insertBook(Book p); // CartItem에 도서 정보를 등록하는 메서드
void removeCart(int numId); // 장바구니 순번 numId의 항목을 삭제하는 메서드
void deleteBook(); // 장바구니의 모든 항목을 삭제하는 메서드
}
Class Cart - 수정
- printBookList(), insertBook(), deleteBook(), printCart(), isCartInBook(), removeCart() 수정
package com.market.cart;
import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
public class Cart implements CartInterface { // CartInterface 인터페이스의 자식 클래스 Cart 생성
public ArrayList<CartItem> mCartItem = new ArrayList<CartItem>(); // mCartItem은 ArrayList 클래스를 이용하여 장바구니에 항목을 담는 객체
// 변수
// static final int NUM_BOOK = 3; // 이전 내용 주석
// public CartItem[] mCartItem = new CartItem[NUM_BOOK]; // 이전 내용 주석
public static int mCartCount = 0; // 장바구니에 담긴 항목의 총 개수를 저장하는 변수
public Cart() { // Cart 클래스의 기본 생성자
}
public void printBookList(ArrayList<Book> booklist) { // Book[] booklist -> ArrayList<Book> 전체 도서 정보 목록 출력 구현
/* 이전 내용 주석
* for(int i = 0; i< booklist.length; i++) {
* System.out.print(booklist[i].getBookId() + " | ");
* System.out.print(booklist[i].getName() + " | ");
* System.out.print(booklist[i].getUnitPrice() + " | ");
* System.out.print(booklist[i].getAuthor() + " | ");
* System.out.print(booklist[i].getDescription() + " | ");
* System.out.print(booklist[i].getCategory() + " | ");
* System.out.print(booklist[i].getReleaseDate() + " | ");
* System.out.println("");
*/
for (int i = 0; i < booklist.size(); i++) {
Book bookitem = booklist.get(i);
System.out.print(bookitem.getBookId() + " | ");
System.out.print(bookitem.getName() + " | ");
System.out.print(bookitem.getUnitPrice() + " | ");
System.out.print(bookitem.getAuthor() + " | ");
System.out.print(bookitem.getDescription() + " | ");
System.out.print(bookitem.getCategory() + " | ");
System.out.print(bookitem.getReleaseDate() + " | ");
System.out.println("");
}
}
public void insertBook(Book book) { // CartItem에 도서 정보를 등록하는 메서드 구현
// mCartItem[mCartCount++] = new CartItem(book); 이전 내용 주석
CartItem bookitem = new CartItem(book);
mCartItem.add(bookitem);
mCartCount = mCartItem.size();
}
public void deleteBook() { // 장바구니의 모든 항목을 삭제하는 메서드 구현
// mCartItem = new CartItem[NUM_BOOK]; 이전 내용 주석
mCartItem.clear();
mCartCount = 0;
}
public void printCart() {
System.out.println("장바구니 상품 목록 :");
System.out.println("-----------------------------------------------");
System.out.println(" 도서ID \t| 수 량 \t| 합 계");
/* 이전 내용 주석
* for(int i = 0; i < mCartCount; i++) {
* System.out.print(" "+mCartItem[i].getBookID() + "\t| ");
* System.out.print(" "+mCartItem[i].getQuantity() + "\t| ");
* System.out.print(" "+mCartItem[i].getTotalPrice());
* System.out.println(" "); }
*/
for (int i = 0; i < mCartCount; i++) {
System.out.print(" " + mCartItem.get(i).getBookID() + "\t| ");
System.out.print(" " + mCartItem.get(i).getQuantity() + "\t| ");
System.out.print(" " + mCartItem.get(i).getTotalPrice());
System.out.println(" ");
}
System.out.println("-----------------------------------------------");
}
public boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드 구현
boolean flag = false;
/* 이전 내용 주석
* for(int i = 0; i < mCartCount; i++) { if(bookId == mCartItem[i].getBookID())
* { mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
*/
for (int i = 0; i < mCartItem.size(); i++) {
if (bookId == mCartItem.get(i).getBookID()) {
mCartItem.get(i).setQuantity(mCartItem.get(i).getQuantity() + 1);
flag = true;
}
}
return flag;
}
public void removeCart(int numId) { // 장바구니 순번 numId의 항목을 삭제하는 메서드 구현
/* 이전 내용 주석
* CartItem[] cartItem = new CartItem[NUM_BOOK]; int num = 0;
*
* for (int i = 0; i < mCartCount; i++) if (numId != i) cartItem[num++] =
* mCartItem[i];
*
*
* mCartCount = num; mCartItem = cartItem;
*/
mCartItem.remove(numId);
mCartCount = mCartItem.size();
}
}
Class Welcome - 수정
- menuCartAddItem(), menuCartRemoveItem(), setFileToBookList(), printBill() 수정
package com.market.main;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언
import com.market.exception.CartException; // CartException 사용하기 위한 선언
public class Welcome {
static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
// static int mCartCount = 0;
static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
static User mUser;
public static void menuIntroduction() { // 메뉴 출력하는 메서드
System.out.println("***************************************");
System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
System.out.println(" 7. 영수증 표시하기 \t8. 종료");
System.out.println(" 9. 관리자 로그인");
System.out.println("***************************************");
}
public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
System.out.println("현재 고객 정보 : ");
System.out.println("이름 " + mUser.getName() + " 연락처 " + mUser.getPhone());
// System.out.println("이름 " + name + " 연락처 " + mobile);
// Person person = new Person(name, mobile);
// System.out.println("이름 " + person.getName() + " 연락처 " + person.getPhone());
}
public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
/*
* System.out.println("장바구니 상품 목록 :");
* System.out.println("-----------------------------------------------");
* System.out.println(" 도서ID \t| 수 량 \t| 합 계"); for(int i = 0; i
* < mCartCount; i++) { System.out.print(" "+mCartItem[i].getBookID() +
* "\t| "); System.out.print(" "+mCartItem[i].getQuantity() + "\t| ");
* System.out.println(" "+mCartItem[i].getTotalPrice()); }
* System.out.println("-----------------------------------------------");
*/
if (mCart.mCartCount >= 0) {
mCart.printCart();
}
}
public static void menuCartClear() throws CartException { // 장바구니 모든 항목 삭제하는 메서드
// System.out.println("장바구니 비우기: ");
if (mCart.mCartCount == 0) {
throw new CartException("장바구니에 항목이 없습니다");
// System.out.println("장바구니에 항목이 없습니다");
} else {
System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
if (str.toUpperCase().equals("Y")) {
mCart.deleteBook();
}
}
}
public static void menuCartAddItem(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book> 변경 매개변수 추가, 장바구니에 도서를
// 추가하는 메서드
// System.out.println("장바구니에 항목 추가하기 : ");
// BookList(book); // 도서 정보를 저장하는 메서드 호출
BookList(booklist);
/*
* for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력 for (int j = 0; j <
* NUM_ITEM; j++) System.out.print(book[i][j] + " | "); System.out.println("");
* }
*/
mCart.printBookList(booklist);
boolean quit = false;
while (!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
Scanner input = new Scanner(System.in);
String str = input.nextLine(); // 도서의 ID를 입력받음
boolean flag = false;
int numId = -1;
/* PART 11 내용 주석
for (int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
if (str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
// 반복문 종료
numId = i;
flag = true;
break;
}
}
*/
for (int i = 0; i < booklist.size(); i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
if (str.equals(booklist.get(i).getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
// 반복문 종료
numId = i;
flag = true;
break;
}
}
if (flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해
// 주세요' 출력
System.out.println("장바구니에 추가하겠습니까? Y | N");
str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
/* PART 11 내용 주석
if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");
// 장바구니에 넣기
if (!isCartInBook(booklist[numId].getBookId()))
mCart.insertBook(booklist[numId]);
}
*/
if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
System.out.println(booklist.get(numId).getBookId() + "도서가 장바구니에 추가되었습니다.");
// 장바구니에 넣기
if (!isCartInBook(booklist.get(numId).getBookId()))
mCart.insertBook(booklist.get(numId));
}
quit = true;
} else
System.out.println("다시 입력해 주세요");
}
}
public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
/*
* boolean flag = false; for(int i = 0; i < mCartCount; i++) { if(bookId ==
* mCartItem[i].getBookID()) {
* mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
* return flag;
*/
return mCart.isCartInBook(bookId);
}
public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
System.out.println("5. 장바구니의 항목 수량 줄이기");
}
public static void menuCartRemoveItem() throws CartException { // 장바구니의 항목 삭제하는 메서드
// System.out.println("6. 장바구니의 항목 삭제하기");
if (mCart.mCartCount == 0)
throw new CartException("장바구니에 항목이 없습니다");
// System.out.println("장바구니에 항목이 없습니다");
else {
menuCartItemList();
boolean quit = false;
while (!quit) {
System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
boolean flag = false;
int numId = -1;
for (int i = 0; i < mCart.mCartCount; i++) {
// if (str.equals(mCart.mCartItem[i].getBookID())) { // PART 11 내용 주석
if (str.equals(mCart.mCartItem.get(i).getBookID())) {
numId = i;
flag = true;
break;
}
}
if (flag) {
System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
str = input.nextLine();
if (str.toUpperCase().equals("Y")) {
// System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다."); // PART 11 내용 주석
System.out.println(mCart.mCartItem.get(numId).getBookID() + "도서가 삭제되었습니다.");
mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
}
quit = true;
} else
System.out.println("다시 입력해 주세요");
}
}
}
public static void menuCartBill() throws CartException { // 주문 처리를 위한 고객의 정보 저장하는 메서드
// System.out.println("7. 영수증 표시하기");
if (mCart.mCartCount == 0)
throw new CartException("장바구니에 항목이 없습니다");
// System.out.println("장바구니에 항목이 없습니다.");
else {
System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
if (str.toUpperCase().equals("Y")) {
System.out.println("배송지를 입력해주세요 ");
String address = input.nextLine();
printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한
// printBill 메서드 호출
} else {
System.out.print("배송받을 고객명을 입력하세요 ");
String name = input.nextLine();
System.out.print("배송받을 고객의 연락처를 입력하세요 ");
String phone = input.nextLine();
System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
String address = input.nextLine();
printBill(name, phone, address);
}
}
}
public static void printBill(String name, String phone, String address) { // 주문 처리 후 영수증을 표시하는 메서드
Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println();
System.out.println("----------------배송받을 고객 정보-----------------");
System.out.println("고객명 : " + name + " \t\t연락처 : " + phone);
System.out.println("배송지 : " + address + " \t\t발송일 : " + strDate);
mCart.printCart(); // 장바구니에 담긴 항목 출력
int sum = 0;
for (int i = 0; i < mCart.mCartCount; i++)
// sum += mCart.mCartItem[i].getTotalPrice(); // PART 11 내용 주석
sum += mCart.mCartItem.get(i).getTotalPrice();
System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
System.out.println("-----------------------------------------------");
System.out.println();
}
public static void menuExit() { // 종료하는 메서드
System.out.println("8. 종료");
}
public static void menuAdminLogin() { // 관리자 로그인 메서드
System.out.println("관리자 정보를 입력하세요");
Scanner input = new Scanner(System.in);
System.out.print("아이디: ");
String adminId = input.next();
System.out.print("비밀번호: ");
String adminPW = input.next();
Admin admin = new Admin(mUser.getName(), mUser.getPhone());
if (adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
String[] writeBook = new String[7];
System.out.println("도서 정보를 추가하겠습니까? Y | N " );
String str = input.next();
if(str.toUpperCase().equals("Y")) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
String strDate = formatter.format(date);
writeBook[0] = "ISBN" + strDate;
System.out.println("도서ID : " + writeBook[0]);
String st1 = input.nextLine(); // 키보드로 한 행 입력시 엔터키를 입력으로 처리
System.out.print("도서명 : ");
writeBook[1] = input.nextLine();
System.out.print("가격 : ");
writeBook[2] = input.nextLine();
System.out.print("저자 : ");
writeBook[3] = input.nextLine();
System.out.print("설명 : ");
writeBook[4] = input.nextLine();
System.out.print("분야 : ");
writeBook[5] = input.nextLine();
System.out.print("출판일 : ");
writeBook[6] = input.nextLine();
try { // 파일 처리를 위한 try ~ catch 문
FileWriter fw = new FileWriter("book.txt", true); // book.txt 파일에 쓰기 위해 FileWriter 객체 생성
// 기존 파일에 쓰기 위해 FileWriter 생성자에 true 작성
for(int i = 0; i < 7; i++) { // 새로 입력받은 도서정보를 book.txt 파일에 저장
fw.write(writeBook[i]+"\n");
}
fw.close(); // FileWriter 객체 종료
System.out.println("새 도서 정보가 저장되었습니다.");
} catch(Exception e) {
System.out.println(e);
}
}else {
System.out.println("이름 " + admin.getName() + " 연락처 " + admin.getPhone());
System.out.println("아이디 " + admin.getId() + " 비밀번호 " + admin.getPassword());
}
} else
System.out.println("관리자 정보가 일치하지 않습니다.");
}
public static void BookList(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book> 도서 정보를 저장하는 메서드
setFileToBookList(booklist);
/*
* booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
* booklist[0].setAuthor("송미영");
* booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
* booklist[0].setCategory("IT전문서");
* booklist[0].setReleaseDate("2018/10/08");
*
* booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
* booklist[1].setAuthor("우재남");
* booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
* booklist[1].setCategory("IT전문서");
* booklist[1].setReleaseDate("2022/01/22");
*
* booklist[2] = new Book("ISBN1236", "스크래치", 22000);
* booklist[2].setAuthor("고광일");
* booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
* booklist[2].setCategory("컴퓨터입문");
* booklist[2].setReleaseDate("2019/06/10");
*/
/*
* book[0][0] = "ISBN1234";
* book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
* book[0][2] = "27000"; // 27,000
* book[0][3] = "송미영";
* book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
* book[0][5] = "IT전문서";
* book[0][6] = "2018/10/08";
* book[1][0] = "ISBN1235";
* book[1][1] = "안드로이드 프로그래밍";
* book[1][2] = "33000"; // 33,000
* book[1][3] = "우재남";
* book[1][4] = "실습 단계별 명쾌한 멘토링!";
* book[1][5] = "IT전문서";
* book[1][6] = "2022/01/22";
* book[2][0] = "ISBN1236";
* book[2][1] = "스크래치";
* book[2][2] = "22000"; // 22,000
* book[2][3] = "고광일";
* book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
* book[2][5] = "컴퓨터입문";
* book[2][6] = "2019/06/10";
*/
}
public static int totalFileToBookList() { // 파일에서 도서의 개수를 얻는 메서드
try {
FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성
String str;
int num = 0;
while ((str = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때 까지 반복
if (str.contains("ISBN")) // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서의 개수 num을 1 증가시킴
++num;
}
reader.close(); // BufferedReader 객체 종료
fr.close(); // FileReader 객체 종료
return num;
} catch (Exception e) {
System.out.println(e);
}
return 0;
}
public static void setFileToBookList(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book> 파일에서 도서 정보 목록을 읽어 저장하는 매서드
try {
FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성
String str2;
String[] readBook = new String[7];
// int count = 0; // PART 11 내용 주석
while ((str2 = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때까지 반복
if (str2.contains("ISBN")) { // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서 정보에 대해 한 행씩 읽어 지역변수 readBook에 저장
readBook[0] = str2;
readBook[1] = reader.readLine();
readBook[2] = reader.readLine();
readBook[3] = reader.readLine();
readBook[4] = reader.readLine();
readBook[5] = reader.readLine();
readBook[6] = reader.readLine();
}
// booklist[count++] = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]); // PART 11 내용 주석
Book bookitem = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]);
booklist.add(bookitem);
}
reader.close(); // BufferedReader 객체 종료
fr.close(); // FileReader 객체 종료
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원
// 배열로 생성
// Book[] mBookList = new Book[NUM_BOOK];
//Book[] mBookList; // 도서 정보를 저장하기 위한 배열 // PART 11 내용 주석
ArrayList<Book> mBookList;
int mTotalBook = 0; // 도서 개수를 저장하기 위한 변수
Scanner input = new Scanner(System.in);
System.out.print("당신의 이름을 입력하세요 : ");
String userName = input.next();
System.out.print("연락처를 입력하세요 : ");
int userMobile = input.nextInt();
mUser = new User(userName, userMobile);
String greeting = "Welcome to Shopping Mall";
String tagline = "Welcome to Book Market!";
boolean quit = false; // 종료 여부 설정 변수
while (!quit) { // quit 변수가 true일 때까지 계속 반복
System.out.println("***************************************");
System.out.println("\t" + greeting);
System.out.println("\t" + tagline);
/*
* 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
* System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
* System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
* System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
* System.out.println("7. 영수증 표시하기 \t8. 종료");
* System.out.println("***************************************");
*/
menuIntroduction(); // 메뉴 목록 출력 메서드 호출
try {
System.out.println("메뉴 번호를 선택해주세요 ");
int n = input.nextInt();
// System.out.println(n +"n번을 선택했습니다. ");
if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
System.out.println("1부터 8까지의 숫자를 입력하세요.");
}
else {
switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
case 1:
/*
* 기존 내용 주석 처리 System.out.println("현재 고객 정보 : "); System.out.println("이름 " +
* userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
*/
menuGuestInfo(userName, userMobile);
break;
case 2:
// System.out.println("장바구니 상품 목록 보기 : ");
menuCartItemList();
break;
case 3:
// System.out.println("장바구니 비우기: ");
menuCartClear();
break;
case 4:
// System.out.println("장바구니에 항목 추가하기 : ");
// menuCartAddItem(mbook);
mTotalBook = totalFileToBookList(); // totalFileToBookList() 호출하여 도서 개수를 mTotalBook에 저장
// mBookList = new Book[mTotalBook]; // 도서 개수 mTotalBook에 따라 도서 정보를 저장하기 위한 배열 mBookList 초기화 // PART 11 내용 주석
mBookList = new ArrayList<Book>();
System.out.println("mTotalbook : "+ mTotalBook);
menuCartAddItem(mBookList);
break;
case 5:
// System.out.println("5. 장바구니의 항목 수량 줄이기");
menuCartRemoveItemCount();
break;
case 6:
// System.out.println("6. 장바구니의 항목 삭제하기");
menuCartRemoveItem();
break;
case 7:
// System.out.println("7. 영수증 표시하기");
menuCartBill();
break;
case 8:
// System.out.println("8. 종료");
menuExit();
quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
break;
case 9:
menuAdminLogin();
break;
}
}
} catch (CartException e) {
System.out.println(e.getMessage());
//quit = true;
}
catch (Exception e) {
System.out.println("올바르지 않은 메뉴 선택으로 종료합니다.");
quit = true;
}
}
}
}
com.market.cart - Cart, CartInterface, CartItem 클래스, mCartItem, mCartCount의 접근제한자 public 추가
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가
com.market.main - Welcome 클래스
클래스 Welcome - 수정
- menuCartBill() 수정
- printBill() 추가
- import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 - import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언 - import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언 - import com.market.member.User; // User 클래스 사용하기 위한 선언
package com.market.main;
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언
public class Welcome {
static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
// static int mCartCount = 0;
static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
static User mUser;
public static void menuIntroduction() { // 메뉴 출력하는 메서드
System.out.println("***************************************");
System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
System.out.println(" 7. 영수증 표시하기 \t8. 종료");
System.out.println(" 9. 관리자 로그인");
System.out.println("***************************************");
}
public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
System.out.println("현재 고객 정보 : ");
System.out.println("이름 "+ mUser.getName() + " 연락처 " + mUser.getPhone());
// System.out.println("이름 " + name + " 연락처 " + mobile);
// Person person = new Person(name, mobile);
// System.out.println("이름 " + person.getName() + " 연락처 " + person.getPhone());
}
public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
/*
System.out.println("장바구니 상품 목록 :");
System.out.println("-----------------------------------------------");
System.out.println(" 도서ID \t| 수 량 \t| 합 계");
for(int i = 0; i < mCartCount; i++) {
System.out.print(" "+mCartItem[i].getBookID() + "\t| ");
System.out.print(" "+mCartItem[i].getQuantity() + "\t| ");
System.out.println(" "+mCartItem[i].getTotalPrice());
}
System.out.println("-----------------------------------------------");
*/
if(mCart.mCartCount >= 0) {
mCart.printCart();
}
}
public static void menuCartClear() { // 장바구니 모든 항목 삭제하는 메서드
//System.out.println("장바구니 비우기: ");
if(mCart.mCartCount == 0) {
System.out.println("장바구니에 항목이 없습니다");
}
else {
System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
if(str.toUpperCase().equals("Y")) {
mCart.deleteBook();
}
}
}
public static void menuCartAddItem(Book[] booklist) { // String[][] book -> Book[] booklist 변경 매개변수 추가, 장바구니에 도서를 추가하는 메서드
// System.out.println("장바구니에 항목 추가하기 : ");
//BookList(book); // 도서 정보를 저장하는 메서드 호출
BookList(booklist);
/*
for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
for (int j = 0; j < NUM_ITEM; j++)
System.out.print(book[i][j] + " | ");
System.out.println("");
}
*/
mCart.printBookList(booklist);
boolean quit = false;
while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
Scanner input = new Scanner(System.in);
String str = input.nextLine(); // 도서의 ID를 입력받음
boolean flag = false;
int numId = -1;
for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
if(str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
numId = i;
flag = true;
break;
}
}
if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
System.out.println("장바구니에 추가하겠습니까? Y | N");
str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");
// 장바구니에 넣기
if(!isCartInBook(booklist[numId].getBookId()))
mCart.insertBook(booklist[numId]);
}
quit = true;
} else
System.out.println("다시 입력해 주세요");
}
}
public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
/*
boolean flag = false;
for(int i = 0; i < mCartCount; i++) {
if(bookId == mCartItem[i].getBookID()) {
mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
flag = true;
}
}
return flag;
*/
return mCart.isCartInBook(bookId);
}
public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
System.out.println("5. 장바구니의 항목 수량 줄이기");
}
public static void menuCartRemoveItem() { // 장바구니의 항목 삭제하는 메서드
// System.out.println("6. 장바구니의 항목 삭제하기");
if(mCart.mCartCount == 0)
System.out.println("장바구니에 항목이 없습니다");
else {
menuCartItemList();
boolean quit = false;
while(!quit) {
System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
boolean flag = false;
int numId = -1;
for(int i = 0; i < mCart.mCartCount; i++) {
if(str.equals(mCart.mCartItem[i].getBookID())) {
numId = i;
flag = true;
break;
}
}
if(flag) {
System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
str = input.nextLine();
if (str.toUpperCase().equals("Y")) {
System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다.");
mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
}
quit = true;
}
else System.out.println("다시 입력해 주세요");
}
}
}
public static void menuCartBill() { // 주문 처리를 위한 고객의 정보 저장하는 메서드
// System.out.println("7. 영수증 표시하기");
if(mCart.mCartCount == 0) System.out.println("장바구니에 항목이 없습니다.");
else {
System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
if(str.toUpperCase().equals("Y")) {
System.out.println("배송지를 입력해주세요 ");
String address = input.nextLine();
printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한 printBill 메서드 호출
}
else {
System.out.print("배송받을 고객명을 입력하세요 ");
String name = input.nextLine();
System.out.print("배송받을 고객의 연락처를 입력하세요 ");
String phone = input.nextLine();
System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
String address = input.nextLine();
printBill(name, phone, address);
}
}
}
public static void printBill(String name, String phone, String address) { // 주문 처리 후 영수증을 표시하는 메서드
Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println();
System.out.println("----------------배송받을 고객 정보-----------------");
System.out.println("고객명 : "+ name + " \t\t연락처 : " + phone);
System.out.println("배송지 : "+ address + " \t\t발송일 : " + strDate);
mCart.printCart(); // 장바구니에 담긴 항목 출력
int sum = 0;
for(int i = 0; i < mCart.mCartCount; i++)
sum += mCart.mCartItem[i].getTotalPrice();
System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
System.out.println("-----------------------------------------------");
System.out.println();
}
public static void menuExit() { // 종료하는 메서드
System.out.println("8. 종료");
}
public static void menuAdminLogin() { // 관리자 로그인 메서드
System.out.println("관리자 정보를 입력하세요");
Scanner input = new Scanner(System.in);
System.out.print("아이디: ");
String adminId = input.next();
System.out.print("비밀번호: ");
String adminPW = input.next();
Admin admin = new Admin(mUser.getName(), mUser.getPhone());
if(adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
System.out.println("이름 "+admin.getName() + " 연락처 " + admin.getPhone());
System.out.println("아이디 "+admin.getId() + " 비밀번호 "+admin.getPassword());
}else
System.out.println("관리자 정보가 일치하지 않습니다.");
}
public static void BookList(Book[] booklist) { // 도서 정보를 저장하는 메서드
booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
booklist[0].setAuthor("송미영");
booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
booklist[0].setCategory("IT전문서");
booklist[0].setReleaseDate("2018/10/08");
booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
booklist[1].setAuthor("우재남");
booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
booklist[1].setCategory("IT전문서");
booklist[1].setReleaseDate("2022/01/22");
booklist[2] = new Book("ISBN1236", "스크래치", 22000);
booklist[2].setAuthor("고광일");
booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
booklist[2].setCategory("컴퓨터입문");
booklist[2].setReleaseDate("2019/06/10");
/*
book[0][0] = "ISBN1234";
book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
book[0][2] = "27000"; // 27,000
book[0][3] = "송미영";
book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
book[0][5] = "IT전문서";
book[0][6] = "2018/10/08";
book[1][0] = "ISBN1235";
book[1][1] = "안드로이드 프로그래밍";
book[1][2] = "33000"; // 33,000
book[1][3] = "우재남";
book[1][4] = "실습 단계별 명쾌한 멘토링!";
book[1][5] = "IT전문서";
book[1][6] = "2022/01/22";
book[2][0] = "ISBN1236";
book[2][1] = "스크래치";
book[2][2] = "22000"; // 22,000
book[2][3] = "고광일";
book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
book[2][5] = "컴퓨터입문";
book[2][6] = "2019/06/10";
*/
}
public static void main(String[] args) {
// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
Book[] mBookList = new Book[NUM_BOOK];
Scanner input = new Scanner(System.in);
System.out.print("당신의 이름을 입력하세요 : ");
String userName = input.next();
System.out.print("연락처를 입력하세요 : ");
int userMobile = input.nextInt();
mUser = new User(userName, userMobile);
String greeting = "Welcome to Shopping Mall";
String tagline = "Welcome to Book Market!";
boolean quit = false; // 종료 여부 설정 변수
while (!quit) { // quit 변수가 true일 때까지 계속 반복
System.out.println("***************************************");
System.out.println("\t" + greeting);
System.out.println("\t" + tagline);
/*
* 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
* System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
* System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
* System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
* System.out.println("7. 영수증 표시하기 \t8. 종료");
* System.out.println("***************************************");
*/
menuIntroduction(); // 메뉴 목록 출력 메서드 호출
System.out.println("메뉴 번호를 선택해주세요 ");
int n = input.nextInt();
// System.out.println(n +"n번을 선택했습니다. ");
if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
System.out.println("1부터 8까지의 숫자를 입력하세요.");
}
else {
switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
case 1:
/*
* 기존 내용 주석 처리
* System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
*/
menuGuestInfo(userName, userMobile);
break;
case 2:
// System.out.println("장바구니 상품 목록 보기 : ");
menuCartItemList();
break;
case 3:
// System.out.println("장바구니 비우기: ");
menuCartClear();
break;
case 4:
// System.out.println("장바구니에 항목 추가하기 : ");
//menuCartAddItem(mbook);
menuCartAddItem(mBookList);
break;
case 5:
// System.out.println("5. 장바구니의 항목 수량 줄이기");
menuCartRemoveItemCount();
break;
case 6:
// System.out.println("6. 장바구니의 항목 삭제하기");
menuCartRemoveItem();
break;
case 7:
// System.out.println("7. 영수증 표시하기");
menuCartBill();
break;
case 8:
// System.out.println("8. 종료");
menuExit();
quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
break;
case 9:
menuAdminLogin();
break;
}
}
}
}
}