스프링 (26)

반응형
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");

	// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
	Enumeration en = request.getParameterNames();
	
	while(en.hasMoreElements()) {
		String name = (String)en.nextElement();
		
		String value = request.getParameter(name);
		out.print("<h5>" + name + " : " + value + "</h5>");
	}
	
	// 파라미터 value의 타입은 String
	String productId    = request.getParameter("productId");
	String pname	    = request.getParameter("pname");
	String unitPrice    = request.getParameter("unitPrice");
	String description  = request.getParameter("description");
	String manufacturer = request.getParameter("manufacturer");
	String category     = request.getParameter("category");
	String unitsInStock = request.getParameter("unitsInStock");
	String condition    = request.getParameter("condition");
	String filename     = request.getParameter("filename");
	String quantity     = request.getParameter("quantity");
	
	//unitPrice
	double price = 0d;
	//unitsInStock
	double stock = 0d;
	
	price = Double.parseDouble(unitPrice);
	stock = Double.parseDouble(unitsInStock);
	
	ProductVO productVO = new ProductVO();
	productVO.setProductId(productId); // P1237
	productVO.setPname(pname); // 키보드
	productVO.setUnitPrice(price); // 30000
	productVO.setDescription(description); // 좋은 키보드
	productVO.setManufacturer(manufacturer); // Samsung
	productVO.setCategory(category); // 주변기기
	productVO.setUnitsInStock(stock); // 4
	productVO.setCondition(condition); // Old
	productVO.setFilename(productId+".jpg"); // P1237.jpg
	
	out.print("<p>productVO : " + productVO + "</p>");
	
	// 싱글톤 객체로 생성
	ProductRepository dao = ProductRepository.getInstance();
	dao.addProduct(productVO);
	
	// 목록으로 이동
	response.sendRedirect("products.jsp");
%>
6장 참조

 

https://forest-of-coding.tistory.com/182

 

[스프링] 6장 쇼핑몰 시스템

사전 준비 테이블 생성 --상품 정보 CREATE TABLE PRODUCT( PRODUCT_ID VARCHAR2(10), PNAME VARCHAR2(90), UNIT_PRICE NUMBER, DESCRIPTION VARCHAR2(3000), MANUFACTURER VARCHAR2(90), CATEGORY VARCHAR2(60), UNITS_IN_STOCK NUMBER, CONDITION VARCHAR2(60)

forest-of-coding.tistory.com

 

위의 페이지에 이어서 쇼핑몰 시스템을 개발한다.

 

 

 

 

 

products.jsp

<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 페이지 디렉티브 -->  
<%	//스크립틀릿
	//ProductRepository() 생성자
	//기본 생성자. 3개의 상품 정보를 설정. 
	//그런 후  Product 객체 타입의 List인 listOfProducts 변수에 저장 
	//ProductRepository productDAO = new ProductRepository();
	ProductRepository productDAO = ProductRepository.getInstance();
	
	// ProductVO 제네릭 List 타입의 객체로 모든 상품 목록을 할당함
	List<ProductVO> productVOList = productDAO.getAllProducts();
	//out.print("<p>productVOList : " + productVOList + "</p>");
%>
<!-- java 객체 -> JSTL 변수 -->
<c:set var="productVOList" value="<%=productVOList%>" />
<!DOCTYPE html>
<html>
<head>
<!-- <link rel="stylesheet" -->
<!--    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" />
	
	<div class="jumbotron">
		<div class="container">
			<h1 class="display-3">상품 목록</h1>
		</div>
	</div>
	
	<!-- 상품목록 출력 -->
	<div class="container">
		<div class="row" align="center">
			<c:forEach var="productVO" items="${productVOList}" varStatus="stat">
			<div class="col-md-4">
				<!-- /images/P1234.jpg -->
				<img src="/images/${productVO.filename}" 
					style="width:100%;" alt="${productVO.pname}" title="${productVO.pname}"/>
				<h3>${productVO.pname}</h3>
				<p>${productVO.description}</p>
				<p>${productVO.unitPrice}</p>
				<!--
				요청URI : product.jsp
				요청파라미터 : productId=P1234
				요청방식 : get(목록, 검색, 상세)
				 -->
				<p><a href="product.jsp?productId=${productVO.productId}"
					class="btn btn-secondary" role="button">상세정보&raquo;</a></p>
			</div>
			</c:forEach>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

 

product.jsp

<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	/*
	요청URI : product.jsp
	요청파라미터 : productId=P1234
	요청방식 : get(목록, 검색, 상세)
	*/
	// 싱글톤
	ProductRepository productDAO = 
		ProductRepository.getInstance();
	
	String productId = request.getParameter("productId"); // P1234
	out.print("<p>"+productId+"</p>"); // P1234
	
	ProductVO productVO = productDAO.getProductById(productId);
	out.print("<p>"+productVO+"</p>");
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" /> <!-- 파라미터가 없기 때문에 이렇게 사용 가능 -->

	<!-- --------------------상품상세 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 정보</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img src="/images/<%=productVO.getFilename()%>" 
					style="width:100%;">
			</div>
			<div class="col-md-6">
				<h3><%=productVO.getPname()%></h3>
				<p><%=productVO.getDescription()%></p>
				<p>
					<b>상품 코드 : </b>
					<span class="badge bage-danger">
					<%=productVO.getProductId()%>
					</span>
				</p>
				<p><b>제조사 : </b><%=productVO.getManufacturer()%></p>
				<p><b>분류 : </b><%=productVO.getCategory()%></p>
				<p><b>재고 수 : </b><%=productVO.getUnitsInStock()%></p>
				<h4><%=productVO.getUnitPrice()%></h4>
				<p>
					<!-- 폼태그, 폼페이지 
					action : 요청URI
					요청URI : addCart.jsp
					요청파라미터 : id=P1234
					요청방식 : post
					-->
					<form name="addForm" action="addCart.jsp?productId=<%=productVO.getProductId()%>"
						method="post">
						<!-- 폼데이터 -->
						<!-- 상품 주문 : 장바구니에 상품을 넣음 
						addToCart() : 핸들러 함수
						-->
						<a href="#" class="btn btn-info" onclick="addToCart()">삼품주문&raquo;</a>
						<!-- 장바구니 : 장바구니에 담겨진 상품 목록 확인 -->
						<a href="cart.jsp" class="btn btn-warning">장바구니&raquo;</a>
						<a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
					</form>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

 

ProductRepository.java

package kr.or.ddit.dao;

import java.util.ArrayList;
import java.util.List;

import kr.or.ddit.vo.ProductVO;

public class ProductRepository {
	// 싱글톤 패턴(공유, 객체가 1회 생성)
	private static ProductRepository instance = new ProductRepository();
	public static ProductRepository getInstance() {return instance;}
	
	//상품 목록을 저장할 리스트 작성(전역변수)
	//인터페이스 : 팀장
	//구현클래스 : 팀원들
	private List<ProductVO> listOfProducts = new ArrayList<ProductVO>();
	
	// 기본 생성자, 3개의 상품 정보를 설정
	private ProductRepository() {
		// 스마트폰
		ProductVO phone = new ProductVO("P1234", "iPhone 6s", 800000);
		
		//상품 설명
		phone.setDescription("4.7-inch, 1334x750 Renina HD display."
								+ "8-megapixel iSight Camera");
		//분류
		phone.setCategory("Smart Phone");
		//제조사
		phone.setManufacturer("Apple");
		//재고 수
		phone.setUnitsInStock(1000);
		//신상품 or 중고품 or 재생품
		phone.setCondition("New");
		//이미지 파일명
		phone.setFilename("P1234.jpg");
		//-------------------------------스마트폰 등록 끝--------------------------------
		
		//-------------------------------노트북 등록 시작--------------------------------
		ProductVO notebook = new ProductVO("P1235", "LG PC 그램", 1500000);
		
		//상품 설명
	    notebook.setDescription("13.3-inch, IPS LED display, 5rd Generation"
	          + "Intel Core processors");
	    //분류
	    notebook.setCategory("Notebook");
	    //제조사
	    notebook.setManufacturer("LG");
	    //재고 수
	    notebook.setUnitsInStock(1000);
	    //신상품 or 중고품 or 재생품
	    notebook.setCondition("Refurbished");
	    //이미지 파일명
	    notebook.setFilename("P1235.jpg");
		//-------------------------------노트북 등록 끝--------------------------------
	    
	    //-------------------------------태블릿 등록 시작--------------------------------
	    ProductVO tablet = new ProductVO("P1236", "Galaxy Tab S", 900000);
	  
	    //상품 설명
	    tablet.setDescription("212.8*125.6*6.6m, Super AMOLED display, "
	          + "Octa-Core processor");
	    //분류
	    tablet.setCategory("Tablet");
	    //제조사
	    phone.setManufacturer("Samsung");
	    //재고 수
	    tablet.setUnitsInStock(1000);
	    //신상품 or 중고품 or 재생품
	    tablet.setCondition("Old");
	    //이미지 파일명
	    tablet.setFilename("P1236.jpg");
	    //-------------------------------태블릿 등록 끝--------------------------------
	    
	    // VO들이 모여서 VO List가 됨
	    listOfProducts.add(phone);
	    listOfProducts.add(notebook);
	    listOfProducts.add(tablet);
	}
	
	// SELECT * FROM PRODUCT
	// 상품 목록
	public List<ProductVO> getAllProducts(){
		return listOfProducts;
	}
	
	// SELECT * FROM PRODUCT
	// WHERE PRODUCT_ID = 'P1234';
	// 특정 상품 불러오기(1행 = 1개의 VO = 1개의 상품)
	public ProductVO getProductById(String productId) {
		ProductVO productById = null;
		
		for(ProductVO productVO : listOfProducts) {
			if (productVO.getProductId().equals(productId)) {
				productById = productVO;
				break;
			}
		}
		return productById;
	}
	
}

 

결과 화면1

 

결과 화면2

 

 

 

등록 화면 추가

 

 

products.jsp

<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 페이지 디렉티브 -->  
<%	//스크립틀릿
	//ProductRepository() 생성자
	//기본 생성자. 3개의 상품 정보를 설정. 
	//그런 후  Product 객체 타입의 List인 listOfProducts 변수에 저장 
	//ProductRepository productDAO = new ProductRepository();
	ProductRepository productDAO = ProductRepository.getInstance();
	
	// ProductVO 제네릭 List 타입의 객체로 모든 상품 목록을 할당함
	List<ProductVO> productVOList = productDAO.getAllProducts();
	//out.print("<p>productVOList : " + productVOList + "</p>");
%>
<!-- java 객체 -> JSTL 변수 -->
<c:set var="productVOList" value="<%=productVOList%>" />
<!DOCTYPE html>
<html>
<head>
<!-- <link rel="stylesheet" -->
<!--    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" />
	
	<div class="jumbotron">
		<div class="container">
			<h1 class="display-3">상품 목록</h1>
		</div>
	</div>
	
	<!-- 상품목록 출력 -->
	<div class="container">
		<div class="row" align="center">
			<c:forEach var="productVO" items="${productVOList}" varStatus="stat">
			<div class="col-md-4">
				<!-- /images/P1234.jpg -->
				<img src="/images/${productVO.filename}" 
					style="width:100%;" alt="${productVO.pname}" title="${productVO.pname}"/>
				<h3>${productVO.pname}</h3>
				<p>${productVO.description}</p>
				<p>${productVO.unitPrice}</p>
				<!--
				요청URI : product.jsp
				요청파라미터 : productId=P1234
				요청방식 : get(목록, 검색, 상세)
				 -->
				<p><a href="product.jsp?productId=${productVO.productId}"
					class="btn btn-secondary" role="button">상세정보&raquo;</a></p>
			</div>
			</c:forEach>
		</div>
		<div class="form-group row">
			<div class="col-sm-offset-2 col-sm-10">
				<a href="addProduct.jsp" class="btn btn-primary">등록</a>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

 

addProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" />

	<!-- --------------------상품등록 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 등록</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<!-- 폼태그, 폼페이지 -->
		<form name="newProduct" action="processAddProduct.jsp" method="post"
			class="form-horizontal">
			<div class="form-group row">
				<!-- 후보키(N.N, N.D) -> 중 1 속성 선택 -> 기본키(N.N, N.D) -->
				<label class="col-sm-2">상품 아이디</label>
				<div class="col-sm-3">
					<input type="text" id="productId" name="productId"
						class="form-controler" placeholder="상품 아이디" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 명</label>
				<div class="col-sm-3">
					<input type="text" id="pname" name="pname"
						class="form-controler" placeholder="상품 명" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 가격</label>
				<div class="col-sm-3">
					<input type="number" id="unitPrice" name="unitPrice"
						class="form-controler" placeholder="상품 가격" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 설명</label>
				<div class="col-sm-3">
					<input type="text" id="description" name="description"
						class="form-controler" placeholder="상품 설명" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">제조사</label>
				<div class="col-sm-3">
					<input type="text" id="manufacturer" name="manufacturer"
						class="form-controler" placeholder="제조사"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">분류</label>
				<div class="col-sm-3">
					<input type="text" id="category" name="category"
						class="form-controler" placeholder="분류"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">재고 수</label>
				<div class="col-sm-3">
					<input type="number" id="unitsInStock" name="unitsInStock"
						class="form-controler" placeholder="재고 수"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">제품 상태</label>
				<div class="col-sm-5">
					<input type="radio" name="condition" value="New" id="condition1"/><label for="condition1">신상품</label>
					<input type="radio" name="condition" value="Old" id="condition2"/><label for="condition3">중고</label>
					<input type="radio" name="condition" value="Refurbished" id="condition3"/><label for="condition3">재생품</label>
				</div>
			</div>
			<div class="form-group row">
				<div class="col-sm-offset-2 col-sm-10">
					<input type="submit" class="btn btn-primary" value="등록" />
					<button type="button" class="btn btn-info" 
						onclick="javascript:location.href='products.jsp'">목록보기</button>
				</div>
			</div>
		</form>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

 

processAddProduct.jsp

<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");

	// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
	Enumeration en = request.getParameterNames();
	
	while(en.hasMoreElements()) {
		String name = (String)en.nextElement();
		
		String value = request.getParameter(name);
		out.print("<h5>" + name + " : " + value + "</h5>");
	}
%>

 

processAddProduct.jsp : 값 나온 것 확인

 

VO에 값을 넣는 작업이 필요함

 

 

=> 값을 넣고 페이지 이동

<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");

	// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
	Enumeration en = request.getParameterNames();
	
	while(en.hasMoreElements()) {
		String name = (String)en.nextElement();
		
		String value = request.getParameter(name);
		out.print("<h5>" + name + " : " + value + "</h5>");
	}
	
	// 파라미터 value의 타입은 String
	String productId    = request.getParameter("productId");
	String pname	    = request.getParameter("pname");
	String unitPrice    = request.getParameter("unitPrice");
	String description  = request.getParameter("description");
	String manufacturer = request.getParameter("manufacturer");
	String category     = request.getParameter("category");
	String unitsInStock = request.getParameter("unitsInStock");
	String condition    = request.getParameter("condition");
	String filename     = request.getParameter("filename");
	String quantity     = request.getParameter("quantity");
	
	//unitPrice
	double price = 0d;
	//unitsInStock
	double stock = 0d;
	
	price = Double.parseDouble(unitPrice);
	stock = Double.parseDouble(unitsInStock);
	
	ProductVO productVO = new ProductVO();
	productVO.setProductId(productId); // P1237
	productVO.setPname(pname); // 키보드
	productVO.setUnitPrice(price); // 30000
	productVO.setDescription(description); // 좋은 키보드
	productVO.setManufacturer(manufacturer); // Samsung
	productVO.setCategory(category); // 주변기기
	productVO.setUnitsInStock(stock); // 4
	productVO.setCondition(condition); // Old
	
	out.print("<p>productVO : " + productVO + "</p>");
	
	// 싱글톤 객체로 생성
	ProductRepository dao = ProductRepository.getInstance();
	dao.addProduct(productVO);
	
	// 목록으로 이동
	response.sendRedirect("products.jsp");
%>

 

 

결과 화면3

 

결과 화면4

 

 

 

파일 첨부

 

 

jquery 사용

 

 

addProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript">
// 동일 jsp 내에 1개의 달러function
// document 내의 모든 요소들이 로딩된 후에 실행
$(function(){
	console.log("개똥이");
	
	// object를 선택(<input type="file" ..)
	$("#productImage").on("change", handleImg);
	
	// e : onchange 이벤트
	function handleImg(e) {
		console.log("파일 선택 이벤트");
		//e.target : <input type="file" id="productImage" name="productImage" class="form-control"...
		let files = e.target.files; // 파일들
		
		// fileArr = [a.jpg, b.jpg, c.jpg]
		let fileArr = Array.prototype.slice.call(files);
		
		// f : 파일(a.jpg)
		fileArr.forEach(function(f) {
			// 이미지 체킹 (MIME타입)
			if(!f.type.match("image.*")) {
				alert("이미지만 가능합니다.");
				return; // handleImg함수 자체를 종료
			}
			// 이미지가 맞다면
			let reader = new FileReader();
			
			//e : reader가 이미지 객체를 읽는 이벤트
			reader.onload = function(e) {
				let img_html = "<img src='" + e.target.result + "' style='width:100%' />";
				// <p id="pImg"><img src='oewrpasdofiasdo..' ../></p>
				// 요소.append : 누적, 요소.html : 새로고침 , 요소.innerHTML : Javascript에서 새로고침
				$("#pImg").append(img_html);
			}
			reader.readAsDataURL(f);
		});
	}
});

</script>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" />

	<!-- --------------------상품등록 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 등록</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<!-- 폼태그, 폼페이지 -->
		<form name="newProduct" action="processAddProduct.jsp" method="post"
			class="form-horizontal">
			<div class="form-group row">
				<!-- 후보키(N.N, N.D) -> 중 1 속성 선택 -> 기본키(N.N, N.D) -->
				<label class="col-sm-2">상품 아이디</label>
				<div class="col-sm-3">
					<input type="text" id="productId" name="productId"
						class="form-controler" placeholder="상품 아이디" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 명</label>
				<div class="col-sm-3">
					<input type="text" id="pname" name="pname"
						class="form-controler" placeholder="상품 명" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 가격</label>
				<div class="col-sm-3">
					<input type="number" id="unitPrice" name="unitPrice"
						class="form-controler" placeholder="상품 가격" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">상품 설명</label>
				<div class="col-sm-3">
					<input type="text" id="description" name="description"
						class="form-controler" placeholder="상품 설명" required/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">제조사</label>
				<div class="col-sm-3">
					<input type="text" id="manufacturer" name="manufacturer"
						class="form-controler" placeholder="제조사"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">분류</label>
				<div class="col-sm-3">
					<input type="text" id="category" name="category"
						class="form-controler" placeholder="분류"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">재고 수</label>
				<div class="col-sm-3">
					<input type="number" id="unitsInStock" name="unitsInStock"
						class="form-controler" placeholder="재고 수"/>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">제품 상태</label>
				<div class="col-sm-5">
					<input type="radio" name="condition" value="New" id="condition1"/><label for="condition1">신상품</label>
					<input type="radio" name="condition" value="Old" id="condition2"/><label for="condition3">중고</label>
					<input type="radio" name="condition" value="Refurbished" id="condition3"/><label for="condition3">재생품</label>
				</div>
			</div>
			<div class="form-group row">
				<label class="col-sm-2">제품 이미지</label>
				<div class="col-sm-5">
				<p id="pImg"></p>
					<input type="file" id="productImage" name="productImage" class="form-control" 
						placeholder="제품 이미지" multiple/>
				</div>
			</div>
			<div class="form-group row">
				<div class="col-sm-offset-2 col-sm-10">
					<input type="submit" class="btn btn-primary" value="등록" />
					<button type="button" class="btn btn-info" 
						onclick="javascript:location.href='products.jsp'">목록보기</button>
				</div>
			</div>
		</form>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

결과 화면5

 

 

반응형

'스프링' 카테고리의 다른 글

[스프링] 11장 파일 업로드  (0) 2024.04.09
[스프링] 10.5장 과제  (0) 2024.04.08
[스프링] 8.5장 과제  (0) 2024.04.01
[스프링] 8장 response 객체  (0) 2024.04.01
[스프링] 7장 내장 객체, request 객체  (0) 2024.04.01
반응형

 

연습문제 01

 

폼 페이지에서 입력된 데이터를 전달하는 요청 파라미터 값을 JSP 페이지로 가져오는 내장 객체는 무엇인지, 그리고 관련된 메소드에 대해 간단히 설명하시오.

 

더보기

request 내장 객체

 

getParameter(String name)

파라미터 이름이 name인 값을 전달받으며 반환 유형은 String이다.

 

 

 

연습문제 02

 

서버에서 웹 브라우저에 다른 페이지로 강제 이동하도록 명령하는 내장 객체와 관련된 메소드는 무엇인가?

 

더보기

redirection

 

sendRedirect(String url)

설정한 URL 페이지로 강제 이동하게 하며 반환 유형은 void이다.

 

 

 

연습문제 03

 

스크립트 태그의 표현문과 같이 데이터를 출력하는 내장 객체는 무엇인가?

 

 

 

 

연습문제 04

 

request 내장 객체를 이용하여 다음 조건에 맞게 JSP 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

더보기

request.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<form action="request_process.jsp" method="get">
		<p>아이디 : 
			<input type="text" name="id" />
		</p>
		<p>비밀번호 : 
			<input type="text" name="passwd" />
		</p>
		<input type="submit" value="전송">
	</form>
</body>
</html>

 

 

request_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<p>
		전송된 요청 파라미터 : 
		<%
			String id = (String)request.getQueryString();
			out.print(id);
		%>
	</p>
</body>
</html>

 

결과 화면1

  

결과 화면2

 

 

 

연습문제 05

 

response 내장 객체를 이용하여 다음 조건에 맞게 JSP 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

더보기

response.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.Calendar"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<%
		response.setIntHeader("Refresh", 5);
	
		SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
		Calendar cal = Calendar.getInstance();
		String am_pm = "";
		int hou = cal.HOUR;
		if(cal.HOUR / 12 == 0) {
			am_pm = "AM";
		} else {
			am_pm = "PM";
			hou = hou-12;
		}
		
		String cale = hou + ":" + sdf.format(cal.getTime()) + am_pm;
	%>
	<p>현재 시간은 <%out.print(cale);%></p>
	<p><a href="response_data.jsp">Google 홈페이지로 이동하기</a></p>
</body>
</html>

 

 

response_data.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%
		response.sendRedirect("https://www.google.com");
	%>
</body>
</html>

 

결과 화면3

 

결과 화면4

 

 

반응형

'스프링' 카테고리의 다른 글

[스프링] 10.5장 과제  (0) 2024.04.08
[스프링] 10장 쇼핑몰 시스템2  (0) 2024.04.02
[스프링] 8장 response 객체  (0) 2024.04.01
[스프링] 7장 내장 객체, request 객체  (0) 2024.04.01
[스프링] 6.5장 과제  (0) 2024.04.01
반응형

 

response

 

: 서버가 요청에 대한 답변을 클라이언트에게 보내는 것. (사용자 요청에 응답)

서버 :  응답 헤더 + 처리 결과 데이터 => 웹 브라우저로 전송

 

 

 

  • 페이지 이동 관련 메소드

페이지 이동 = 리다이렉션(redirection)

페이지 이동 시에는 문자 인코딩에 알맞게 설정해야함

 

 

- forwarding과 redirect 의 차이

forwarding (JSP)

: 상세 페이지를 볼 때 주로 사용

 

redirect (URL)

: 값을 변경, 삭제, 등록 등 후에 이동할 때 사용

 

 

 

  • 페이지 이동 관련 메소드 종류
페이지 이동 관련 메소드 반환 유형 설명
sendRedirect(String url) void 설정한 URL 페이지로 강제 이동

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects(내장 객체)</title>
</head>
<body>
	<%	// 스크립틀릿
		// redirect : 새로운 URL로 이동
		response.sendRedirect("http://www.google.com");
	%>
</body>
</html>

 

결과 화면1 : URL를 localhost/ch05/response.jsp 로 입력 시 구글 페이지로 이동

 

 

 

response 객체 예시1

 

 

response01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Object</title>
</head>
<body>
	<!-- 
	   요청URI : response01_process.jsp
	   요청파라미터(쿼리스트링) : id=a001&passwd=java
	   요청방식 : post
    -->
	<form action="response01_process.jsp" method="post">
		<!-- 폼데이터 -->
		<p>아이디 : <input type="text" name="id" placeholder="아이디" required /></p>
		<p>비밀번호 : <input type="password" name="passwd" placeholder="비밀번호" required /></p>
		<p><input type="submit" value="전송" /></p>
		
	</form>
</body>
</html>

 

 

response01_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<%	// 스크립틀릿
	/* 요청URI : response01_process.jsp
	요청파라미터(쿼리스트링) : request{id=a001&passwd=java}
	요청방식 : post
	*/
	request.setCharacterEncoding("UTF-8");
	
	String id = request.getParameter("id"); // a001
	String passwd = request.getParameter("passwd"); // java
	
	out.print("<p>id : " + id + "</p>");
	out.print("<p>passwd : " + passwd + "</p>");
%>
</body>
</html>

 

결과 화면2-1

 

결과 화면2-2

 

 

 

response01_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<%	// 스크립틀릿
	/* 요청URI : response01_process.jsp
	요청파라미터(쿼리스트링) : request{id=a001&passwd=java}
	요청방식 : post
	*/
	request.setCharacterEncoding("UTF-8");
	
	String id = request.getParameter("id"); // a001
	String passwd = request.getParameter("passwd"); // java
	
	out.print("<p>id : " + id + "</p>");
	out.print("<p>passwd : " + passwd + "</p>");
	
	/*
	비교
	1) 숫자 == 숫자, 객체 == 객체
	2) 문자열.equals(문자열)
	*/
	if(id.equals("a001")&&passwd.equals("java")) { // 관리자
		// redirect : 새로운 URL
		response.sendRedirect("response01_sucess.jsp");
	} else { // 일반
		// redirect : 새로운 URL 재요청
		response.sendRedirect("response01_failed.jsp");
	}
%>
</body>
</html>

 

 

response01_sucess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<h3>관리자 로그인 성공</h3>
</body>
</html>

 

 

response01_failed.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<h3>관리자 로그인 실패!</h3>
	<!-- redirect?(x)-자동처리 -> a link-수동처리 -->
	<p><a href="response01.jsp">로그인가기</a></p>
</body>
</html>

 

결과 화면3-1 : id는 a001, password는 java로 로그인 시 뜸

 

결과 화면3-2 : 아이디와 비밀번호 다른 것 입력 시 뜨는 화면

 

 

 

  • 5초마다 JSP 페이지 갱신
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<h3>이 페이지는 5초마다 새로고침 됩니다.</h3>
	<%	// 스크립틀릿
		response.setIntHeader("Refresh", 5); // 5초마다 새로고침
	%>
	<p><%=new Date()%>
	<p><%=new Date().toLocaleString()%>
</body>
</html>

 

결과 화면4

 

 

 

응답 HTTP 헤더 관련 메소드 ( response 객체 예시2)

 

 

응답 HTTP 헤더 관련 메소드 반환 유형 설명
addCookie(Cookie cookie) void 쿠키를 추가
addDateHeader(String name, long date) void 헤더 이름 name에 날짜/시간을 추가
addHeader(String name, String value) void 헤더 이름 name에 value 추가
addIntHeader(String name, int value) void 헤더 이름 name에 정수 value 추가
setDateHeader(String name, long date) void 헤더 이름 name에 날짜/시간 설정
setHeader(String name, String value) void 헤더 이름 name에 문자열 값 value 설정
setIntHeader(String name, int value) void 헤더 이름 name에 정수값 value 설정
containsHeader(String name) boolean 헤더 이름 name이 HTTP 헤더에 포함되었는지 여부 확인
포함됨 - true
포함되지 않음 - false
getHeader(String name) String 헤더 이름 name 값을 가져옴

 

 

 

response0101.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<% // 스크립틀릿
		response.setHeader("Cache-control", "use_chache");
		response.setHeader("contentType", "text/html;charset=UTF-8");
		response.setDateHeader("date", 1L);
	%>
	<p>Cache-control : <%=response.getHeader("Cache-control")%> </p>
	<p>contentType : <%=response.getHeader("contentType")%></p>
	<p>date : <%=response.getHeader("date")%></p>
</body>
</html>

 

결과 화면5

 

 

 

response 객체 예시3 (응답 콘텐츠 관련 메소드)

 

 

응답 콘텐츠 관련 메소드 반환 유형 설명
setContentType(String type) void 응답한 MIME 유형 설정
getContentType() String 응답한 MIME 유형 가져옴
setCharacterEncoding(String charset) void 응답할 문자 인코딩 설정
getCharacterEncoding() String 응답할 문자 인코딩 가져옴
sendError(int status_code, String message) void 응답할 오류(코드 및 오류 메시지) 설정
setStatus(int statuscode) void 응답할 HTTP 코드 설정

 

 

 

  • sendError
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%	// 스크립틀릿
		response.sendError(404, "요청 페이지를 찾을 수 없습니다");
	%>
</body>
</html>

 

결과 화면6

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%	// 스크립틀릿
		// HTTP STATUS CODE
		response.sendError(200, "성공");
// 		response.sendError(404, "요청 페이지를 찾을 수 없습니다");

		out.print("<p>"+(3+2) +"</p>"); // 위의 코드로 인해 가려짐
	%>
</body>
</html>

 

결과 화면7

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<%	// 스크립틀릿
		// HTTP STATUS CODE
// 		response.sendError(200, "성공");
// 		response.sendError(404, "요청 페이지를 찾을 수 없습니다");
		response.sendError(500, "개발자 오류");

		out.print("<p>"+(3+2) +"</p>"); // 위의 코드로 인해 가려짐
	%>
</body>
</html>

 

결과 화면8

 

 

반응형

'스프링' 카테고리의 다른 글

[스프링] 10장 쇼핑몰 시스템2  (0) 2024.04.02
[스프링] 8.5장 과제  (0) 2024.04.01
[스프링] 7장 내장 객체, request 객체  (0) 2024.04.01
[스프링] 6.5장 과제  (0) 2024.04.01
[스프링] 6장 쇼핑몰 시스템  (0) 2024.03.29
1 ··· 3 4 5 6 7 8 9