관리 메뉴

거니의 velog

231101_JSP 과제 3 본문

대덕인재개발원_웹기반 애플리케이션

231101_JSP 과제 3

Unlimited00 2023. 11. 1. 13:50

[p. 178-180]




[request.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<form action="request_process.jsp" method="get">
			<label for="id">아이디 : </label>
			<input id="id" name="id" type="text" /><br />
			<label for="pw">비밀번호 : </label>
			<input id="pw" name="pw" type="text" /><br />
			<button type="submit">전송</button>
		</form>
	</body>
</html>

[request_process.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<% 
			String queryStr = request.getQueryString();
			//System.out.println(queryStr);
			
			String id = null;
			String pw = null;
			
			if(queryStr != null) {
				String[] parameters = queryStr.split("&");
				for(String parameter : parameters) {
					String[] parts = parameter.split("=");
					if(parts.length == 2) {
						if("id".equals(parts[0])) {
							id = parts[1];
						}else if("pw".equals(parts[0])) {
							pw = parts[1];
						}
					}
				}
			}
		%>
		<p>
			전송된 요청 파라미터 : <%= queryStr %>
		</p>
		<p>
			get 방식으로 보낸 id값 : <%= id %>
		</p>
		<p>
			get 방식으로 보낸 pw값 : <%= pw %>
		</p>
	</body>
</html>

- http://localhost/request.jsp


[response.jsp]

<%@page import="java.util.Date"%>
<%@page import="java.util.Calendar"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<% 
			// header 정보 중, Refresh 헤더를 이용해 5초마다 페이지를 새로고침한다.
			response.setIntHeader("Refresh", 5);
		
			Calendar cal = Calendar.getInstance();
			int hour = cal.get(Calendar.HOUR);
			int minute = cal.get(Calendar.MINUTE);
	        int second = cal.get(Calendar.SECOND);
	        String amPm = cal.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
	        
	        String formattedHour = String.format("%02d", hour);
	        String formattedMinute = String.format("%02d", minute);
	        String formattedSecond = String.format("%02d", second);
	        
		%>
		<p>
			현재 시간은 <%= formattedHour %> : <%= formattedMinute %> : <%= formattedSecond %> <%= amPm %>
		</p>
		<a href="./response_data.jsp">Google 홈페이지로 이동하기</a>
	</body>
</html>

[response_data.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	response.sendRedirect("https://www.google.co.kr/");
%>

- http://localhost/response.jsp


[Book.java]

package vo;

import java.io.Serializable;

public class Book implements Serializable {

	private static final long serialVersionUID = -4274700572038677000L;

	private String bookId; 		    // 책 ID
	private String name;			// 책이름
	private Integer unitPrice; 		// 가격
	private String author;			// 저자
	private String description; 	// 설명
	private String publisher;	    // 출판사
	private String category; 		// 분류
	private long unitsInStock; 		// 재고개수
	private long totalPages; 		// 페이지수
	private String releaseDate;   	// 출판일(월/년)
	private String condition; 		// 신제품
	private String filename;		// 파일명
	private int quantity;			// 장바구니 담는 갯수

	public Book() {}
	public Book(String bookId, String name, Integer unitPrice) {		
		this.bookId = bookId;
		this.name = name;
		this.unitPrice = unitPrice;
	}

	public String getBookId() {
		return bookId;
	}
	public void setBookId(String bookId) {
		this.bookId = bookId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer  getUnitPrice() {
		return unitPrice;
	}
	public void setUnitPrice(Integer  unitPrice) {
		this.unitPrice = unitPrice;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getPublisher() {
		return publisher;
	}
	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public long getUnitsInStock() {
		return unitsInStock;
	}
	public void setUnitsInStock(long unitsInStock) {
		this.unitsInStock = unitsInStock;
	}
	public long getTotalPages() {
		return totalPages;
	}
	public void setTotalPages(long totalPages) {
		this.totalPages = totalPages;
	}
	public String getReleaseDate() {
		return releaseDate;
	}
	public void setReleaseDate(String releaseDate) {
		this.releaseDate = releaseDate;
	}
	public String getCondition() {
		return condition;
	}
	public void setCondition(String condition) {
		this.condition = condition;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	
	@Override
	public String toString() {
		return "Book [bookId=" + bookId + ", name=" + name + ", unitPrice=" + unitPrice + ", author=" + author
				+ ", description=" + description + ", publisher=" + publisher + ", category=" + category
				+ ", unitsInStock=" + unitsInStock + ", totalPages=" + totalPages + ", releaseDate=" + releaseDate
				+ ", condition=" + condition + ", filename=" + filename + ", quantity=" + quantity + "]";
	}
	
}

[BookRepository.java]

package dao;

import java.util.ArrayList;

import vo.Book;

public class BookRepository{
	
	private ArrayList<Book> listOfBooks = new ArrayList<Book>();
	private static BookRepository instance = new BookRepository();
	public static BookRepository getInstance() {
		return instance;
	}
	
	public BookRepository() {
		Book book1= new Book("ISBN1234","HTML5+CSS3", 15000);
		book1.setAuthor("황재호");
		book1.setDescription("워드나 PPT 문서를 만들 수 있나요? 그러면 문제 없습니다. 지금 바로 웹페이지 제작에 도전해보세요. 지금 당장 컴퓨터가 없어도 괜찮습니다. 코드와 실행 화면이 바로 보여서 눈으로만 읽어도 어떻게 작동하는지 쉽게 파악할 수 있는 것은 기본이고, 중간중간 퀴즈를 추가하여 재미있게 게임하듯 복습할 수 있습니다.");
		book1.setPublisher("한빛미디어");
		book1.setCategory("Hello Coding");
		book1.setUnitsInStock(1000);
		book1.setTotalPages(288);
		book1.setReleaseDate("2018/03/02");
		book1.setFilename("ISBN1234.jpg");
		
		Book book2 = new Book("ISBN1235","쉽게 배우는 자바 프로그래밍", 27000);
		book2.setAuthor("우종중");
		book2.setDescription("객체 지향의 핵심과 자바의 현대적 기능을 충실히 다루면서도초보자가 쉽게 학습할 수 있게 구성했습니다. 시각화 도구를 활용한 개념 설명과 군더더기 없는 핵심 코드를 통해 개념과 구현을 한 흐름으로 학습할 수 있습니다. 또한 ‘기초 체력을 다지는 예제 → 셀프 테스트 → 생각을 논리적으로 정리하며 한 단계씩 풀어 가는 도전 과제 → 스토리가 가미된 흥미로운 프로그래밍 문제’ 등을 통해 프로그래밍 실력을 차근차근 끌어올릴 수 있습니다");
		book2.setPublisher("한빛아카데미");
		book2.setCategory("IT모바일");
		book2.setUnitsInStock(1000);
		book2.setTotalPages(692);
		book2.setReleaseDate("2017/08/02");
		book2.setFilename("ISBN1235.jpg");
		
		Book book3= new Book("ISBN1236","스프링4 입문 ", 27000);
		book3.setAuthor("하세가와 유이치 , 오오노 와타루 , 토키 코헤이(권은철 , 전민수 ) ");
		book3.setDescription("스프링은 단순히 사용 방법만 익히는 것보다 아키텍처를 어떻게 이해하고 설계하는지가 더 중요합니다. 예제를 복사해 붙여넣는 식으로는 실제 개발에서 스프링을 제대로 활용할 수 없습니다. 이 책에서는 웹 애플리케이션의 기초를 다지고 스프링 코어를 살펴보며 클라우드 네이티브 입문까지 다룹니다. 이제 막 실무에 뛰어든 웹 애플리케이션 초급자나 개발 경험은 있지만 스프링은 사용해본 적 없는 분을 대상으로 가능한 한 쉽게 설명합니다 ");
		book3.setPublisher("한빛미디어");
		book3.setCategory("IT모바일");
		book3.setUnitsInStock(1000);
		book3.setTotalPages(520);
		book3.setReleaseDate("2017/11/01");
		book3.setFilename("ISBN1236.jpg");
		
		listOfBooks.add(book1);
		listOfBooks.add(book2);
		listOfBooks.add(book3);
	}
	
	public ArrayList<Book> getAllBooks() {
		return listOfBooks;
	}

	public Book getBookById(String bookId) {
		Book bookById = null;

		for (int i = 0; i < listOfBooks.size(); i++) {
			Book book = listOfBooks.get(i);
			if (book != null && book.getBookId() != null && book.getBookId().equals(bookId)) {
				
				bookById = book;
				break;
			}
		}
		return bookById;
	}
	
	public void addBook(Book book) {
		listOfBooks.add(book);
	}

}

[menu.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
		<nav class="navbar navbar-expand navbar-dark bg-dark">
			<div class="container">
				<div class="navbar-header">
					<a class="navbar-brand" href="./welcome.jsp">Home</a>
				</div>
			</div>
		</nav>

[footer.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
		<footer class="container">
			<p>&copy; BookMarket</p>
		</footer>

[books.jsp]

<%@page import="vo.Book"%>
<%@page import="java.util.ArrayList"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
	<head>
		<link rel="stylesheet" href="${pageContext.request.contextPath }/resources/css/bootstrap.min.css" />
		<title>도서 목록</title>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 목록</h1>
			</div>
		</div>
	      
		<div class="container">	
			<% 
				BookRepository dao = BookRepository.getInstance();
				ArrayList<Book> listOfBook = dao.getAllBooks();
			%>
			<% 
				for(int i = 0; i < listOfBook.size(); i++) {
					Book book = listOfBook.get(i);
			%>
			<div class="row">
				<!--
				<div class="col-md-3" align="center">	
					<img src="${pageContext.request.contextPath }/resources/images/" width="60%">
				</div>
				-->
				<div class="col-md-10">	
					<h5 ><b>[<%= book.getCategory() %>] <%= book.getName() %></b></h5>
					<p style="padding-top: 10px"><%= book.getDescription() %></p> 
					<p><%= book.getAuthor() %> | <%= book.getPublisher() %> | <%= book.getUnitPrice() %> 원</p>
				</div>	
				<div class="col-md-2"  style="padding-top: 60px">						    			 
					<a href="./book.jsp?id=<%= book.getBookId() %>" class="btn btn-secondary" role="button"> 상세정보 &raquo; </a>				
				</div>
			</div>
			<hr />
			<% 
				}
			%>			
		</div>	
		<%@ include file="footer.jsp" %>
	</body>
</html>

[book.jsp]

<%@page import="vo.Book"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<link rel="stylesheet" href="${pageContext.request.contextPath }/resources/css/bootstrap.min.css" />
		<title>도서 정보</title>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 정보</h1>
			</div>
		</div>
		<div class="container">
			<% 
				String id = request.getParameter("id");
				BookRepository dao = BookRepository.getInstance();
				Book book = dao.getBookById(id);
			%>
			<div class="row">
				<!--
				<div class="col-md-4">
					<img src="${pageContext.request.contextPath }/resources/images/" style="width: 100%" />
				</div>
				-->
				<div class="col-md-12">
					<h4><b>[<%= book.getCategory() %>] <%= book.getName() %></b></h4>
					<p><%= book.getDescription() %></p>
					<p><b>도서코드 : </b><span class="badge badge-danger"><%= book.getBookId() %></span></p>
					<p><b>출판사</b> : <%= book.getPublisher() %></p>			
					<p><b>저자</b> : <%= book.getAuthor() %></p>			
					<p><b>재고수</b> : <%= book.getUnitsInStock() %></p>
					<p><b>총 페이지수</b> : <%= book.getTotalPages() %></p>
					<p><b>출판일</b> : <%= book.getReleaseDate() %></p>
					<h4>가격 : <%= book.getUnitPrice() %></h4>
					<form name="addForm" action="./addCart.jsp" method="get">
						<input type="hidden" value="" name="id"/>
						<a href="#" class="btn btn-info" onclick="addToCart()"> 도서주문&raquo;</a> 
						<a href="./cart.jsp" class="btn btn-warning"> 장바구니&raquo;</a> 
						<a href="./books.jsp" class="btn btn-secondary">도서목록 &raquo;</a>
					</form>
				</div>
			</div>
			<hr>
		</div>
		<%@ include file="footer.jsp" %>
	</body>
</html>

- http://localhost/books.jsp

'대덕인재개발원_웹기반 애플리케이션' 카테고리의 다른 글

231103_JSP 개론 7  (0) 2023.11.03
231102_JSP 개론 6  (0) 2023.11.02
231101_JSP 개론 5  (0) 2023.11.01
231031_JSP 과제 정리  (0) 2023.10.31
231031_JSP 개론 4  (0) 2023.10.31