관리 메뉴

거니의 velog

231103_JSP 개론 7 본문

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

231103_JSP 개론 7

Unlimited00 2023. 11. 3. 08:27

* get 방식에 쿼리스트링으로 담긴 값(id)은 우선 순위가 떨어짐. input 에 담긴 name 값이 헤더에 먼저 들어감. 그리고 쿼리 스트링을 재구성하기 때문에 id 값은 날아가 버림.

* post 방식일 때 쿼리 스트링의 id는 헤더로, input의 name 은 바디로 데이터가 둘 다 들어간다

* 데이터를 어떻게 검증해야 할까? 개발자 도구의 네트워크 탭에서 요청 내역을 보고, 요청을 클릭하면 옆의 창이 활성화 됨. 이 안에 payload를 확인해야 한다.


* C:\upload\파일명.png => 내가 사용하는 OS의 특정 경로임. 이것을 http://localhost/c:\\upload로 경로가 설정되면 잘못된 경로이다. 이 뒤에 나오는 경로 자체를 시스템 경로가 아닌 웹 서버 안에 들어 있는 업로드 경로로 바꿔 주어야 한다.

* 즉, 내가 만든 사이트가 돌아가는 톰캣의 실제 경로를 필요로 한다.

* 웹 서버로 접근하는 요청 URL이 있을 것이다. 즉, 웹 서버 안에 들어 있는 업로드 Path를 설정해 주어야 접근할 수 있다는 말.

* .metadata 폴더를 잘 살펴보자.

- D:\A_TeachingMaterial\07_JSP_Spring\workspace\workspace_jsp\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps

- localhost/resources/images/Penguins.jpg


*  request.getContextPath : 절대경로. ROOT. => Project 명인지, /WebContent 인지 물어보는 것.
   - server 탭에 /로 설정하면? / 이면서 ROOT

==> D:\A_TeachingMaterial\07_JSP_Spring\workspace\workspace_jsp\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JSPBook

 

* request.getContextPath.getRealPath 로 설정가능. 이 경우는 서버 업로드에 해당하는 폴더임.

   request.getContextPath.getRealPath ("/resources/images");


[ProductRepository.java]

package dao;

import java.util.ArrayList;

import vo.Product;

public class ProductRepository {

	// 상품 모두를 가지고 있을 리스트
	private ArrayList<Product> listOfProducts = new ArrayList<Product>();
	
	// 싱글턴 적용
	private static ProductRepository instance = new ProductRepository();
	public static ProductRepository getInstance() {
		return instance;
	}
	
	public ProductRepository() {
		Product phone = new Product("P1234", "iPhone 6s", 800000);
		phone.setDescription("4.7-inch, 1334X750 Retina HD Display, 8-megapixel iSight Camera");
		phone.setCategory("Smart Phone");
		phone.setMenufacturer("Apple");
		phone.setUnitsInStock(1000);
		phone.setCondition("New");
		phone.setFilename("P1234.png");
		
		Product notebook = new Product("P1235", "LG PC 그램", 1500000);
		notebook.setDescription("13.3inch, IPS LED display, 5rd Generation Intel Core processors");
		notebook.setCategory("Notebook");
		notebook.setMenufacturer("LG");
		notebook.setUnitsInStock(1000);
		notebook.setCondition("Refurbished");
		notebook.setFilename("P1235.png");
		
		Product tablet = new Product("P1236", "Galaxy Tab S", 900000);
		tablet.setDescription("232.8*123.6*6.6mm, Super AMOLED display, Octa-Core processors");
		tablet.setCategory("Tablet");
		tablet.setMenufacturer("Samsung");
		tablet.setUnitsInStock(1000);
		tablet.setCondition("Old");
		tablet.setFilename("P1236.png");
		
		listOfProducts.add(phone);
		listOfProducts.add(notebook);
		listOfProducts.add(tablet);
	}
	
	// 상품 전체 목록 가져오기
	public ArrayList<Product> getAllProducts() {
		return listOfProducts;
	}
	
	// 하나의 상품 가져오기
	public Product getProductById(String productId) {
		Product productById = null;
		
		for(int i = 0; i < listOfProducts.size(); i++) {
			Product product = listOfProducts.get(i);
			if(product != null && product.getproductId() != null && product.getproductId().equals(productId)) {
				productById = product;
				break;
			}
		}
		return productById;
	}
	
	// 상품 등록하기
	public void addProduct(Product product) {
		listOfProducts.add(product);
	}
	
}

[products.jsp]

<img src="${pageContext.request.contextPath }/resources/images/<%= product.getFilename() %>" style="width: 100%"/>

[product.jsp]

<div class="col-md-5">
	<img alt="" src="${pageContext.request.contextPath }/resources/images/<%= product.getFilename() %>" style="width: 100%"/>
</div>

[addProduct.jsp]

<form name="newProduct" action="processAddProduct.jsp" class="form-horizontal" method="post" enctype="multipart/form-data">

...

<div class="form-group row">
    <label class="col-sm-2">이미지</label>
    <div class="col-sm-5">
        <input type="file" name="productImage" class="form-control">
    </div>
</div>

[processAddProduct.jsp]

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@page import="java.io.File"%>
<%@page import="vo.Product"%>
<%@page import="dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");

	// String realFolder = request.getRealPath("/") + "upload"; // 이 녀석은 더 이상 사용하지 않는다.
	
	// 웹 애플리케이션 상의 절대 경로
	String realFolder = request.getServletContext().getRealPath("/resources/images");
	String encType = "UTF-8"; // 인코딩 타입
	
	int maxSize = 5 * 1024 * 1024; // 최대 업로드 될 파일 크기(5MB)
	
	File folder = new File(realFolder);
	if(!folder.exists()) {
		folder.mkdirs();
	}
	
	DiskFileUpload upload = new DiskFileUpload();
	upload.setSizeMax(1000000); // 최대 크기
	upload.setSizeThreshold(maxSize); // 메모리 상에 저장할 최대 크리(byte)
	upload.setRepositoryPath(realFolder); // 업로드 된 파일을 임시로 저장할 경로
	
	List items = upload.parseRequest(request);
	Iterator params = items.iterator();
	
	// 데이터를 저장하기 위한 변수 설정
	String productId = "";
	String name = "";
	String unitPrice = "";
	String description = "";
	String manufacturer = "";
	String category = "";
	String unitsInStock = "";
	String condition = "";
	String fileName = "";

	// 일반적인 데이터를 저장할 때 사용 (방법 1)
	/* String productId = request.getParameter("productId");
	String name = request.getParameter("name");
	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"); */
	
	while(params.hasNext()) {
		FileItem item = (FileItem) params.next();
		
		if(item.isFormField()) { // 일반 데이터일때
			String fieldName = item.getFieldName();
			
			// 일반적인 input 요소로 넘어온 name(key)을 이용하여 값을 할당
			if(fieldName.equals("productId")) {
				productId = item.getString(encType);
			}else if(fieldName.equals("name")){
				name = item.getString(encType);
			}else if(fieldName.equals("unitPrice")){
				unitPrice = item.getString(encType);
			}else if(fieldName.equals("description")){
				description = item.getString(encType);
			}else if(fieldName.equals("manufacturer")){
				manufacturer = item.getString(encType);
			}else if(fieldName.equals("category")){
				category = item.getString(encType);
			}else if(fieldName.equals("unitsInStock")){
				unitsInStock = item.getString(encType);
			}else if(fieldName.equals("condition")){
				condition = item.getString(encType);
			}
		}else { // 파일 데이터일때
			String fileFieldName = item.getFieldName(); // 요청 파라미터 이름
			fileName = item.getName(); // 저장 파일의 이름
			String contentType = item.getContentType(); // 파일 컨텐츠 타입
			long fileSize = item.getSize(); // 파일 크기 정보
			File saveFile = new File(realFolder + "/" + fileName);
			item.write(saveFile); // 파일 복사
		}
	}
	
	// 가격을 문자에서 숫자로 변경
	Integer price;
	if(unitPrice.isEmpty()){
		price = 0;
	}else {
		price = Integer.valueOf(unitPrice);
	}
	
	// 재고수를 문자에서 숫자로 변경
	long stock;
	if(unitsInStock.isEmpty()){
		stock = 0;
	}else {
		stock = Long.valueOf(unitsInStock);
	}
	
	ProductRepository dao = ProductRepository.getInstance();
	
	Product product = new Product();
	product.setproductId(productId);
	product.setPname(name);
	product.setUnitPrice(price);
	product.setDescription(description);
	product.setMenufacturer(manufacturer);
	product.setCategory(category);
	product.setUnitsInStock(stock);
	product.setCondition(condition);
	product.setFilename(fileName);
	
	dao.addProduct(product);
	
	response.sendRedirect("products.jsp");
	
%>

- http://localhost/WebMarket/addProduct.jsp


05장 내장 객체 : 상품 상세 정보 표시하기

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

		request 내장 객체

		__________________________________________________________________________________________________________________________________________________________________

		요청 파라미터 관련 메소드			| 형식				| 설명
		__________________________________________________________________________________________________________________________________________________________________

		getParameter(String name)			| String				| 요청 파라미터 이름이 name인 값을 전달받는다.

		getParameterValues(String name)		| String[]				| 모든 요청 파라미터 이름이 name인 값을 배열 형태로 전달받는다. 요청 파라미터 값이 없으면 null을 반환

		getParameterNames()					| Enumeration			| 모든 요청 파라미터의 이름과 값을 Enumeration 객체 타입으로 전달받는다.

		getParameterMap()					| Map					| 모든 요청 파라미터의 이름과 값을 Map 객체 타입으로 전달 받는다.
											  							(Map 객체 타입은 <파라미터 이름, 값> 형식으로 구성된다.)
		__________________________________________________________________________________________________________________________________________________________________

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

		response 내장 객체

		__________________________________________________________________________________________________________________________________________________________________

		페이지 이동 관련 메소드			| 반환 유형				| 설명
		__________________________________________________________________________________________________________________________________________________________________

		sendRedirect(url)				  | void				  | 설정한 URL 페이지로 강제 이동한다.

		__________________________________________________________________________________________________________________________________________________________________

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

		out 내장 객체

[headPart.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
	    <link rel="shortcut icon" type="image/x-icon" href="/resources/assets/images/favicon.svg" />
	    <link href="https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
	    <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet">
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/bootstrap.min.css" />
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/LineIcons.2.0.css" />
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/animate.css" />
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/tiny-slider.css" />
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/glightbox.min.css" />
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/assets/css/main.css" />
    	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

[validation.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
						<!-- 자바스크립트 onsubmit 이벤트 -->
						<form name="loginForm" action="validation_process.jsp" method="get" onsubmit="return submitEvent()">
							아이디 : <input type="text" name="id" /><br />
							비밀번호 : <input type="text" name="pw" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery form을 이용한 submit 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm2">
							아이디 : <input type="text" name="id2" id="id2" /><br />
							비밀번호 : <input type="text" name="pw2" id="pw2" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery click 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm3">
							아이디 : <input type="text" name="id3" id="id3" /><br />
							비밀번호 : <input type="text" name="pw3" id="pw3" /><br />
							<button type="button" id="loginBtn">전송</button>
						</form>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>
<script type="text/javascript">

	// 자바 스크립트 onsubmit 이벤트 처리
	function submitEvent() {
		console.log("Submit Event...!");
		alert("Submit Event...!");
		
		var id = document.loginForm.id.value;
		var pw = document.loginForm.pw.value;
		
		if(id == "") {
			alert("아이디가 누락되었습니다.");
			return false;
		}
		if(pw == "") {
			alert("비밀번호가 누락되었습니다.");
			return false;
		}
	}
	
</script>
</html>

[validation_process.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
						<% 
							request.setCharacterEncoding("utf-8");
						
							String id = request.getParameter("id");
							String pw = request.getParameter("pw");
							
							out.println("아이디 : " + id + "<br />");
							out.println("비밀번호 : " + pw + "<br />");
						%>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>

</html>

- http://localhost/ch08/validation.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
						<!-- 자바스크립트 onsubmit 이벤트 -->
						<form name="loginForm" action="validation_process.jsp" method="get" onsubmit="return submitEvent()">
							아이디 : <input type="text" name="id" /><br />
							비밀번호 : <input type="text" name="pw" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery form을 이용한 submit 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm2">
							아이디 : <input type="text" name="id2" id="id2" /><br />
							비밀번호 : <input type="text" name="pw2" id="pw2" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery click 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm3">
							아이디 : <input type="text" name="id3" id="id3" /><br />
							비밀번호 : <input type="text" name="pw3" id="pw3" /><br />
							<button type="button" id="loginBtn">전송</button>
						</form>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>
<script type="text/javascript">

	// 자바 스크립트 onsubmit 이벤트 처리
	function submitEvent() {
		console.log("Submit Event...!");
		alert("Submit Event...!");
		
		var id = document.loginForm.id.value;
		var pw = document.loginForm.pw.value;
		
		if(id == "") {
			alert("아이디가 누락되었습니다.");
			return false;
		}
		if(pw == "") {
			alert("비밀번호가 누락되었습니다.");
			return false;
		}
	}
	
	// 제이쿼리를 통한 이벤트 처리
	$(function(){
		var loginForm2 = $("#loginForm2");
		
		loginForm2.submit(function(){
			var id = $("#id2").val();
			var pw = $("#pw2").val();
			
			if(id == "") {
				alert("아이디가 누락되었습니다.");
				return false;
			}
			if(pw == "") {
				alert("비밀번호가 누락되었습니다.");
				return false;
			}
		});
	});
	
</script>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
						
						<!-- 
							input type button/submit은 아주 예전부터 익히 사용되어 왔던 대표적인 버튼 Element이다.
							브라우저 엔진 버전과 HTML 버전이 업그레이드 되면서 input type button/submit 만이 대체할 수 없는
							부분들이 발견되어 새롭게 만들어진 태그가 button 태그이다. input type button/submit은 end 태그
							로서의 활용이 어려워(</input>) CSS를 활용하여 또는 태그들을 활용하여 버튼을 꾸미는데 제약이 많이 걸렸다.
							button 태그는 몸체를 꾸밀 수 있다는 장점도 있어 CSS를 활용하는 건 물론 버튼 태그 내에 다양한 태그를 활용하여
							버튼을 꾸밀 수 있다.
							그리고 input type button/submit에서 제공되는 click, submit 또한 제공된다.
							
							우리가 다양하게 사용하고 있는 버튼 이벤트들 중, submit 이라는 이벤트는 기본적으로 form 태그 내에 있는
							input 요소들의 데이터를 읽어 action에 설정되어 있는 경로로 데이터를 보내주는 역할을 하는데, submit()
							이벤트 자체만으로 본다면 브라우저마다의 엔진별 특징이 조금씩 다르다. 그리고 submit() 이벤트 자체에 컨트롤이
							생각보다 어려운 것도 사실이다. 대표적으로 브라우저의 엔진별 로직과 시점이다. 
							사용자가 사용하는 다양한 환경의 needs를 맞춰 개발하기란 쉽지 않지만 누구나 사용가능한 공통적인 처리 로직을 구현하는 건 어렵지 않다.
							개발자들 사이에서 관례로 사용되는 내용들이 여기에도 포함된다.
							(ex, ServiceImpl에서 impl은 인터페이스를 implement 했다는 증거)
							- input type button/submit 버튼에는 onclick 요소를 활용하여 클릭 이벤트를 함께 주지 않는다.
								> click과 submit 이벤트의 시점과 브라우저 버전별, 엔진 처리 로직의 차이 때문
								
							# onsubmit 속성 이벤트 활용
							- onsubmit 이벤트는 모든 브라우저 지원
							- onsubmit="return 함수명"으로 사용
								> return을 부여하는 건 해당 함수가 실행될 때, 정상적으로 처리되면 true, 값의 필터에 의해 처리 결과가
									비정상적일 땐 false를 리턴한다.
								> 이 때, submit 이벤트가 발생하지 않는다.
								
							# onclick 속성 이벤트 활용
							- input type button의 onclick 속성의 요소를 활용
							- input type button Element에 "click" 이벤트 활용
						 -->
						 
						<!-- 자바스크립트 onsubmit 이벤트 -->
						<form name="loginForm" action="validation_process.jsp" method="get" onsubmit="return submitEvent()">
							아이디 : <input type="text" name="id" /><br />
							비밀번호 : <input type="text" name="pw" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery form을 이용한 submit 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm2">
							아이디 : <input type="text" name="id2" id="id2" /><br />
							비밀번호 : <input type="text" name="pw2" id="pw2" /><br />
							<button type="submit">전송</button>
						</form>
						
						<!-- jQuery click 이벤트 -->
						<form action="validation_process.jsp" method="get" id="loginForm3">
							아이디 : <input type="text" name="id3" id="id3" /><br />
							비밀번호 : <input type="text" name="pw3" id="pw3" /><br />
							<button type="button" id="loginBtn">전송</button>
						</form>
						
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>
<script type="text/javascript">

	// 자바 스크립트 onsubmit 이벤트 처리
	function submitEvent() {
		console.log("Submit Event...!");
		alert("Submit Event...!");
		
		var id = document.loginForm.id.value;
		var pw = document.loginForm.pw.value;
		
		if(id == "") {
			alert("아이디가 누락되었습니다.");
			return false;
		}
		if(pw == "") {
			alert("비밀번호가 누락되었습니다.");
			return false;
		}
	}
	
	// 제이쿼리를 통한 이벤트 처리
	$(function(){
		var loginForm2 = $("#loginForm2");
		
		var loginForm3 = $("#loginForm3");
		var loginBtn = $("#loginBtn");
		
		loginForm2.submit(function(){
			var id = $("#id2").val();
			var pw = $("#pw2").val();
			
			if(id == "") {
				alert("아이디가 누락되었습니다.");
				return false;
			}
			if(pw == "") {
				alert("비밀번호가 누락되었습니다.");
				return false;
			}
		});
		
		loginBtn.on("click", function(){
			var id = $("#id3").val();
			var pw = $("#pw3").val();
			
			if(id == "") {
				alert("아이디가 누락되었습니다.");
				return false;
			}
			if(pw == "") {
				alert("비밀번호가 누락되었습니다.");
				return false;
			}
			
			loginForm3.submit();
		});
		
	});
	
</script>
</html>


[validation01.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
                    
                    	<h3>Javascript 버전</h3>
						<form name="loginForm" action="process.jsp">
							아이디 : <input type="text" name="id" /><br />
							비밀번호 : <input type="text" name="pw" /><br />
							<button type="button" onclick="return checkForm()">전송</button>
						</form>
						
                    	<h3>jQuery 버전</h3>
						<form name="loginForm2" id="loginForm2">
							아이디 : <input type="text" name="id2" id="id2" /><br />
							비밀번호 : <input type="text" name="pw2" id="pw2" /><br />
							<button type="button" id="loginBtn">전송</button>
						</form>
						
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>
<script type="text/javascript">
	
	function checkForm(){
		alert("아이디 : " + document.loginForm.id.value + "\n" + 
				"비밀번호 : " + document.loginForm.pw.value);
	}
	
	$(function(){
		var loginBtn = $("#loginBtn");
		
		loginBtn.on("click", function(){
			alert("아이디 : " + $("#id2").val() + "\n" + 
					"비밀번호 : " + $("#pw2").val());
		});
	});
	
</script>
</html>

- http://localhost/ch08/validation01.jsp


[validation02.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
                    
                    	<h3>Javascript 버전</h3>
						<form name="loginForm" action="validation02_process.jsp">
							아이디 : <input type="text" name="id" /><br />
							비밀번호 : <input type="text" name="pw" /><br />
							<button type="button" onclick="return checkForm()">전송</button>
						</form>
						
                    	<h3>jQuery 버전</h3>
						<form name="loginForm2" id="loginForm2" action="validation02_process.jsp">
							아이디 : <input type="text" name="id2" id="id2" /><br />
							비밀번호 : <input type="text" name="pw2" id="pw2" /><br />
							<button type="button" id="loginBtn">전송</button>
						</form>
						
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>
<script type="text/javascript">
	
	function checkForm(){
		var form = document.loginForm;
		
		// 아이디가 입력되었는지 검사한다.
		// 아이디가 입력되지 않으면 오류 메시지를 출력하고 해당 입력 항목에 커서가 놓인다.
		if(form.id.value == ""){
			alert("아이디를 입력해 주세요.");
			form.id.focus();
			return false;
		}
		
		// 비밀번호가 입력되었는지 검사한다.
		// 비밀번호가 입력되지 않으면 오류 메시지를 출력하고 해당 입력 항목에 커서가 놓인다.
		if(form.pw.value == ""){
			alert("비밀번호를 입력해 주세요.");
			form.pw.focus();
			return false;
		}
		
		// 폼 페이지에서 입력한 데이터 값을 서버로 전송한다.
		form.submit();
	}
	
	$(function(){
		var loginBtn = $("#loginBtn");
		var loginForm2 = $("#loginForm2");
		
		loginBtn.on("click", function(){
			var id = $("#id2").val();
			var pw = $("#pw2").val();
			
			if(id == null || id == "") {
				alert("아이디를 입력해 주세요.");
				$("#id2").focus();
				return false;
			}
			
			if(pw == null || pw == "") {
				alert("비밀번호를 입력해 주세요.");
				$("#pw2").focus();
				return false;
			}
			
			loginForm2.submit();
		});
	});
	
</script>
</html>

- http://localhost/ch08/validation02.jsp

[validation02_process.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>쉽게 배우는 JSP 웹 프로그래밍</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <%@ include file="/pageModule/headPart.jsp" %>
</head>

<body>
    <%@ include file="/pageModule/header.jsp" %>

    <div class="breadcrumbs" style="padding-top:40px;">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">유효성 검사</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">INDEX</a></li>
                        <li>CH08</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <section class="about-us section">
        <div class="container">
            <div class="row align-items-center justify-content-center">
                <div class="col-lg-12 col-md-12 col-12">
                    <div class="content-left wow fadeInLeft" data-wow-delay=".3s">
						<% 
							request.setCharacterEncoding("utf-8");
						
							String id = request.getParameter("id");
							String pw = request.getParameter("pw");
							String id2 = request.getParameter("id2");
							String pw2 = request.getParameter("pw2");
							
							out.println("javascript 버전 <br />");
							out.println("아이디 : " + id + "<br />");
							out.println("비밀번호 : " + pw + "<br />");
							
							out.println("jQuery 버전 <br />");
							out.println("아이디 : " + id2 + "<br />");
							out.println("비밀번호 : " + pw2 + "<br />");
						%>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <%@ include file="/pageModule/footer.jsp" %>

    <%@ include file="/pageModule/footerPart.jsp" %>
</body>

</html>


 

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

231106_JSP 개론 8  (0) 2023.11.06
231103_JSP 과제 4  (0) 2023.11.03
231102_JSP 개론 6  (0) 2023.11.02
231101_JSP 과제 3  (0) 2023.11.01
231101_JSP 개론 5  (0) 2023.11.01