관리 메뉴

거니의 velog

231102_JSP 개론 6 본문

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

231102_JSP 개론 6

Unlimited00 2023. 11. 2. 08:49

[addProduct.jsp]

<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<link rel="stylesheet" 	href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
		<title>상품 등록</title>
	</head>
	<body>
		<%@ include file="menu.jsp" %>	
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-3">상품 등록</h1>
			</div>
		</div>
		<div class="container">
			<form name="newProduct" action="processAddProduct.jsp" class="form-horizontal" method="post">
				<div class="form-group row">
					<label class="col-sm-2">상품 코드</label>
					<div class="col-sm-3">
						<input type="text" name="productId" id="productId" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">상품명</label>
					<div class="col-sm-3">
						<input type="text" name="name" id="name" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">가격</label>
					<div class="col-sm-3">
						<input type="text" name="unitPrice" id="unitPrice" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">상세 정보</label>
					<div class="col-sm-5">
						<textarea name="description" cols="50" rows="2"
							class="form-control"></textarea>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">제조사</label>
					<div class="col-sm-3">
						<input type="text" name="manufacturer" class="form-control">
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">분류</label>
					<div class="col-sm-3">
						<input type="text" name="category" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2">재고 수</label>
					<div class="col-sm-3">
						<input type="text" name="unitsInStock" id="unitsInStock" class="form-control" >
					</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"> 신규 제품 
						<input type="radio" name="condition" value="Old"> 중고 제품 
						<input type="radio" name="condition" value="Refurbished"> 재생 제품
					</div>
				</div>
				<!--
				<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>
				-->
				<div class="form-group row">
					<div class="col-sm-offset-2 col-sm-10 ">
						<input type="submit" class="btn btn-primary" value="등록">
					</div>
				</div>
			</form>
		</div>
	</body>
</html>

[ProductRepository.java]

...

	// 상품 등록하기
	public void addProduct(Product product) {
		listOfProducts.add(product);
	}
    
...

[processAddProduct.jsp]

<%@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 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");
	
	// 가격을 문자에서 숫자로 변경
	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);
	
	dao.addProduct(product);
	
	response.sendRedirect("products.jsp");
	
%>

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


스프링에서도 xml에 설정하는 속성이 디스크파일업로드 클래스 메소드의 1~3번 메소드이다.

[fileupload03.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>CH07</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">
						<form action="fileupload03_process.jsp" method="post" enctype="multipart/form-data">
							파일 : <input type="file" name="filename" /><br />
							<button type="submit">전송</button>
						</form>			
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

</html>

[fileupload03_process.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 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>CH07</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">
						<% 
							// 폼 페이지에서 전송된 파일을 저장할 서버의 경로를 작성
							String fileUploadPath = "C:\\upload";
						
							File file = new File(fileUploadPath);
							if(!file.exists()) { // 설정한 경로에 폴더가 없으면
								file.mkdirs(); // 폴더를 만들어주세요.
							}
							
							// Commons-fileupload를 이용하여 파일을 업로드하려면 제일 먼저 common-fileupload 라이브러리가 필요함.
							// 파일 업로드를 위해 패키지에 포함되어 있는 DiskFileUpload 객체를 생성함.
							DiskFileUpload upload = new DiskFileUpload();
							// 생성된 객체를 통해 DiskFileUpload 클래스가 제공하는 메소드를 사용하여 웹 브라우저가 전송한
							// multipart/form-data 유형의 요청 파라미터를 가져옴.
							// 폼 페이지에서 전송된 요청 파라미터를 전달받도록 DiskFileUpload 객체 타입의 parseRequest() 메소드를 작성
							List items = upload.parseRequest(request);
							// 폼 페이지에서 전송된 요청 파라미터를 Iterator 클래스로 변환
							Iterator params = items.iterator();
							
							// 폼 페이지에서 전송된 요청 파라미터가 없을 때까지 반복하도록 Iterator 객체 타입의
							// hasNext() 메소드를 작성
							while(params.hasNext()) {
								FileItem fileItem = (FileItem) params.next();
								
								if(!fileItem.isFormField()) { // 파일 데이터일 때
									String fileName = fileItem.getName(); // 파일명
									
						%>
									<p><%= fileName %>이 저장되었습니다!</p>
						<%
									// 이곳으로 업로드가 되겠습니다.
									// C:\\upload\\KaKaoTalk_20231102_14_56.jpg
									File newFile = new File(fileUploadPath + "/" + fileName);
									fileItem.write(newFile); // 파일 복사
								}
							}
						%>	
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

</html>

- http://localhost/ch07/fileupload03.jsp


[fileupload04.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>CH07</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">
						<form action="fileupload04_process.jsp" method="post" enctype="multipart/form-data">
							이름 : <input type="text" name="name" /><br />
							제목 : <input type="text" name="title" /><br />
							파일 : <input type="file" name="filename" multiple="multiple" /><br />
							<button type="submit">전송</button>
						</form>			
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

</html>

[fileupload04_process.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 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>CH07</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">
						<% 
							// 폼 페이지에서 전송된 파일을 저장할 서버의 경로를 작성
							String fileUploadPath = "C:\\upload";
						
							File file = new File(fileUploadPath);
							if(!file.exists()) { // 설정한 경로에 폴더가 없으면
								file.mkdirs(); // 폴더를 만들어주세요.
							}
							
							// Commons-fileupload를 이용하여 파일을 업로드하려면 제일 먼저 common-fileupload 라이브러리가 필요함.
							// 파일 업로드를 위해 패키지에 포함되어 있는 DiskFileUpload 객체를 생성함.
							DiskFileUpload upload = new DiskFileUpload();
							
							// 서버로 넘어온 파일에 대한 설정
							upload.setSizeMax(5 * 1024 * 1024); // 업로드 할 파일의 최대 크기(Byte)
							upload.setSizeThreshold(4 * 1024 * 1024); // 메모리상에 저장할 최대 크기(Byte)
							upload.setRepositoryPath(fileUploadPath); // 업로드된 파일을 임시로 저장할 경로
							
							// 생성된 객체를 통해 DiskFileUpload 클래스가 제공하는 메소드를 사용하여 웹 브라우저가 전송한
							// multipart/form-data 유형의 요청 파라미터를 가져옴.
							// 폼 페이지에서 전송된 요청 파라미터를 전달받도록 DiskFileUpload 객체 타입의 parseRequest() 메소드를 작성
							List items = upload.parseRequest(request);
							// 폼 페이지에서 전송된 요청 파라미터를 Iterator 클래스로 변환
							Iterator params = items.iterator();
							
							// 폼 페이지에서 전송된 요청 파라미터가 없을 때까지 반복하도록 Iterator 객체 타입의
							// hasNext() 메소드를 작성
							int maxSize = 4 * 1024 * 1024; // 파일 업로드 시 1개의 파일 당 사이즈(최대사이즈)
							while(params.hasNext()) {
								FileItem fileItem = (FileItem) params.next();
								
								if(fileItem.isFormField()) { // 일반 데이터일 때
									String name = fileItem.getFieldName(); // 파라미터의 이름
									String value = fileItem.getString("UTF-8"); // 파라미터의 값
									out.println(name + "=" + value + "<br />");
								}else { // 파일 데이터일 때
									String fileFieldName = fileItem.getFieldName(); // 요청 파라미터의 이름
									String fileName = fileItem.getName(); // 파일명
									String contentType = fileItem.getContentType(); // 파일 컨텐츠타입(MimeType)
									long fileSize = fileItem.getSize(); // 파일크기
									
									File newFile = new File(fileUploadPath + "/" + fileName);
									
									// 최대크기를 넘어버림(최대사이즈보다 큰 파일이 업로드됨)
									if(maxSize < fileSize) {
										out.println("파일 크기를 초과하였습니다!<br />");
									}else {
										fileItem.write(newFile); // 파일 복사
									}
									
									out.println("〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓<br />");
									out.println("요청 파라미터 이름 : " + fileFieldName + "<br />");
									out.println("저장 파일 이름 : " + fileName + "<br />");
									out.println("파일 컨텐츠 타입 : " + contentType + "<br />");
									out.println("파일 크기 : " + fileSize + "<br />");
								}
							}
						%>	
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

</html>

- http://localhost/ch07/fileupload04.jsp


[MemberVO.java]

package kr.or.ddit.ch07.vo;

public class MemberVO{
	private String mem_id;
	private String mem_pw;
	private String mem_name;
	private String mem_sex;
	private String filename;
	
	public String getMem_id() {
		return mem_id;
	}
	public void setMem_id(String mem_id) {
		this.mem_id = mem_id;
	}
	public String getMem_pw() {
		return mem_pw;
	}
	public void setMem_pw(String mem_pw) {
		this.mem_pw = mem_pw;
	}
	public String getMem_name() {
		return mem_name;
	}
	public void setMem_name(String mem_name) {
		this.mem_name = mem_name;
	}
	public String getMem_sex() {
		return mem_sex;
	}
	public void setMem_sex(String mem_sex) {
		this.mem_sex = mem_sex;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	
	@Override
	public String toString() {
		return "MemberVO [mem_id=" + mem_id + ", mem_pw=" + mem_pw + ", mem_name=" + mem_name + ", mem_sex=" + mem_sex
				+ ", filename=" + filename + "]";
	}
	
}

[MemberDAO.java]

package kr.or.ddit.ch07.dao;

import java.util.ArrayList;

import kr.or.ddit.ch07.vo.MemberVO;

public class MemberDAO{
	
	private ArrayList<MemberVO> memberList = new ArrayList<MemberVO>();
	private static MemberDAO instance = new MemberDAO();
	public static MemberDAO getInstance() {
		return instance;
	}
	
	public ArrayList<MemberVO> getMemberList() {
		return memberList;
	}
	
	public MemberVO getMemberById(String mem_id) {
		MemberVO memberById = null;
		
		for(int i = 0; i < memberList.size(); i++) {
			MemberVO member = memberList.get(i);
			if(member != null && member.getMem_id() != null && member.getMem_id().equals(mem_id)) {
				memberById = member;
				break;
			}
		}
		return memberById;
	}

	public void insertMember(MemberVO member) {
		memberList.add(member);
	}

}

[ch07_test_signin.jsp]

<%@page import="kr.or.ddit.ch07.dao.MemberDAO"%>
<%@page import="kr.or.ddit.ch07.vo.MemberVO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<% 
    String loginfailed = "";
    if (request != null) {
        String idParam = request.getParameter("fail");
        if (idParam != null) {
        	loginfailed = idParam;
        }
    }
%>

<!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" %>
    <script>
    	$(function(){
    		let logfail = <%= loginfailed %>
    		if(!logfail) {
    			alert("아따 로그인에 실패해 부렀당게");
    		}
    	});
    </script>
</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>CH07</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">
						<!--  
							1. 아이디, 비밀번호, 로그인 버튼을 이용하여
								ch07_test_signin_process.jsp로 이동하여 로그인 처리 해주세요.
							2. 로그인 시, 등록된 회원이 존재하지 않는 경우, '존재하지 않는 회원입니다!'
								메시지가 출력되게 해주세요.
							3. 회원가입 버튼을 생성하고, 회원 가입 버튼을 클릭 시 회원가입 페이지로 이동합니다.
						-->
						<form action="ch07_test_signin_process.jsp" method="post" style="margin-bottom: 10px;">
							<label for="userid" style="width: 100%!important; margin-bottom: 10px;">
								<span>아이디 : </span>
								<input id="userid" name="userid" class="form-control" type="text" />
							</label>
							<label for="userpw" style="width: 100%!important; margin-bottom: 10px;">
								<span>비밀번호 : </span>
								<input id="userpw" name="userpw" class="form-control" type="text" />
							</label>
							<button type="submit" class="btn btn-primary">로그인</button>
						</form>
						<a href="ch07_test_signup.jsp" class="btn btn-light">회원가입</a>
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

</html>

[ch07_test_signup.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>CH07</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">
						<!--
							1. 아이디, 비밀번호, 이름, 성별, 프로필 이미지를 입력받고 회원가입을 진행해주세요.
							2. 회원가입 진행 경로는 ch07_test_signup_process.jsp로 이동하여  회원가입 처리를 진행해주세요.
							3. 뒤로가기 버튼을 생성하고, 뒤로가기 버튼을 클릭 시 다시 로그인 화면으로 나갈 수 있도록 해주세요.
						 -->
						 <form action="ch07_test_signup_process.jsp" method="post" enctype="multipart/form-data" style="margin-bottom: 10px;">
							<label for="userid" style="width: 100%!important; margin-bottom: 10px;">
								<span>아이디 : </span>
								<input id="userid" name="userid" class="form-control" type="text" />
							</label>
							<label for="userpw" style="width: 100%!important; margin-bottom: 10px;">
								<span>비밀번호 : </span>
								<input id="userpw" name="userpw" class="form-control" type="text" />
							</label>
							<label for="usernm" style="width: 100%!important; margin-bottom: 10px;">
								<span>이름 : </span>
								<input id="usernm" name="usernm" class="form-control" type="text" />
							</label>
							<div style="margin-bottom: 10px;">
								<span>성별 : </span>
								<input id="gender1" name="gender" type="radio" value="남자" />
								<label for="gender1">&nbsp;남자</label>
								<input id="gender2" name="gender" type="radio" value="여자" />
								<label for="gender2">&nbsp;여자</label>
							</div>
							<div style="margin-bottom: 20px;">
								<label for="userprofile">프로필 이미지</label><br />
								<input id="userprofile" name="userprofile" class="form-control" type="file">
							</div>
							<button type="submit" class="btn btn-primary">가입하기</button>
							<a href="ch07_test_signin.jsp" class="btn btn-secondary">뒤로가기</a>
						</form>
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

[ch07_test_signup_process.jsp]

<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@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="kr.or.ddit.ch07.vo.MemberVO"%>
<%@page import="kr.or.ddit.ch07.dao.MemberDAO"%>
<%@ 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>CH07</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">
						<!--
							1. 회원가입 폼에서 넘겨받은 일반 데이터, 파일 데이터를 전달받아서 일반 데이터와 파일명을 저장하여
								회원 객체 하나를 저장 후, 회원 목록에 해당하는 리스트에 저장하여 목록 페이지에서 리스트 데이터를
								활용할 수 있도록 해주세요.
							2. 회원가입이 완료되면, ch07_test_signin.jsp로 이동하여 로그인을 진행할 수 있도록 해주세요.
						 -->
						 <% 
						 	request.setCharacterEncoding("utf-8");
						 
						 	HashMap data = new HashMap();
						 	
						 	// 파일 업로드
						 	// 웹 애플리케이션 상의 절대 경로
							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 fileName = "";
							
							while(params.hasNext()) {
								FileItem fileItem = (FileItem) params.next();
								
								if(fileItem.isFormField()) { // 일반 데이터일 때
									String name = fileItem.getFieldName(); // 파라미터 이름
									//out.println(name);
									String value = fileItem.getString("UTF-8");
									//out.println(value);
									data.put(name, value);
								}else { // 파일 데이터 일 때
									String fileFieldName = fileItem.getFieldName(); // 요청 파라미터 이름
									fileName = fileItem.getName(); // 저장 파일의 이름
									String contentType = fileItem.getContentType(); // 파일 컨텐츠 타입
									long fileSize = fileItem.getSize(); // 파일 크기 정보
									File saveFile = new File(realFolder + "/" + fileName);
									fileItem.write(saveFile); // 파일 복사
								}
							}
							
						 	// 멤버 등록
						 	MemberDAO memDao = MemberDAO.getInstance();
						 	
						 	MemberVO memVo = new MemberVO();
						 	memVo.setMem_id((String) data.get("userid"));
						 	memVo.setMem_pw((String) data.get("userpw"));
						 	memVo.setMem_name((String) data.get("usernm"));
						 	memVo.setMem_sex((String) data.get("gender"));
						 	memVo.setFilename(fileName);
						 	
						 	memDao.insertMember(memVo);
						 	
						 	response.sendRedirect("ch07_test_signin.jsp");
						 %>
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

[ch07_test_signin_process.jsp]

<%@page import="kr.or.ddit.ch07.vo.MemberVO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.or.ddit.ch07.dao.MemberDAO"%>
<%@ 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>CH07</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">
						<!-- 
							1. 로그인 페이지에서 전송한 아이디, 비밀번호를 받는다.
							2. 전달받은 아이디, 비밀번호에 해당하는 내 정보가 있는지 없는지 체크
								- DAO, VO를 활용하여 진행할 수 있도록 합니다.
								- 제공된 DAO, VO를 사용
							3. 전달받은 아이디, 비밀번호에 해당하는 회원인 경우에 ch07_test_memberList.jsp로 이동하여
								회원 목록 페이지를 완성해주세요.
							4. 전달받은 아이디 비밀번호에 해당하지 않는 회원인 경우에 ch07_test-signin.jsp로 이동하여 
								다시 로그인을 진행할 수 있도록 해주고, 에러 메세지를 출력해주세요! 
						 -->
						 <% 
						 	request.setCharacterEncoding("utf-8");
						 
						 	// 1. 로그인 페이지에서 전송한 아이디, 비밀번호를 받는다.
						 	String userid = request.getParameter("userid");
						 	//System.out.println(userid);
						 	String userpw = request.getParameter("userpw");
						 	//System.out.println(userpw);
						 	
						 	// 2. 전달받은 아이디, 비밀번호에 해당하는 내 정보가 있는지 없는지 체크
						 	MemberDAO memDao = MemberDAO.getInstance();
						 	
						 	MemberVO memVo = memDao.getMemberById(userid);
						 	//System.out.println(memVo.toString());
						 	
						 	if(memVo != null) { // 아이디 검색으로 회원 정보는 검색된 상태 & null 값 체크
						 		if(userid.equals(memVo.getMem_id()) && userpw.equals(memVo.getMem_pw())) { // 로그인 성공
						 			response.sendRedirect("ch07_test_memberList.jsp?id="+userid);
						 		}else { // 로그인 실패
						 			response.sendRedirect("ch07_test_signin.jsp?fail=false");
						 		}
						 	}else{ // 아이디 검색으로 회원 정보가 없는 상태
						 		response.sendRedirect("ch07_test_signin.jsp?fail=false");
						 	}
						 %>
                    </div>
                </div>
            </div>
        </div>
    </section>

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

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

[ch07_test_memberList.jsp]

<%@page import="kr.or.ddit.ch07.dao.MemberDAO"%>
<%@page import="kr.or.ddit.ch07.vo.MemberVO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<% 
    String idVal = "";
    if (request != null) {
    	String idParam = request.getParameter("id");
        if (idParam != null) {
        	idVal = idParam;
        }
    }
%>
    
<!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" %>
    <script>
		$(function(){
			let idVal = "<%= idVal %>";
			alert(idVal + "님! 환영합니다!");
		});
    </script>
</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>CH07</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">
						<!--
							1. 로그인 성공 후, 넘어왔을때 'a001님! 환영합니다!' 메세지 출력을 완성해주세요.
								- 이때 a001은 로그인 시 사용한 아이디입니다
							2. 회원 목록에 저장되어있는 회원 모두를 출력해주세요.
							
								[로그아웃]
								───────────────────────────────────────────────────
									이미지	|		회원정보		|		버튼
								───────────────────────────────────────────────────
											|	아이디 : a001		|	
									이미지	|	비밀번호 : 1234	|	[상세정보]
											|	이름 : 홍길동		|	
											|	성별 : 남자		|
								───────────────────────────────────────────────────
								...
								...
								
							3. 회원등록 버튼을 클릭 시, 회원 가입 페이지로 이동하여 회원 등록을 진행할 수 있도록 해주세요.
									 
						 -->
						 <% 
						 	request.setCharacterEncoding("utf-8");
						 	MemberDAO memDao = MemberDAO.getInstance();
						 	ArrayList<MemberVO> memList = memDao.getMemberList();
						 %>
						 
						 <c:set var="memList" value="<%= memList %>"/>
						 <c:set var="idVal" value="<%= idVal %>"/>
						 
						 <table class="table">
						 	 <tr>
						 		 <th>이미지</th>
						 		 <th>회원정보</th>
						 		 <th>버튼</th>
						 	 </tr>
							 <c:forEach var="memVo" items="${memList}">
							 	<tr>
							 		<td>
							 			<img src="${pageContext.request.contextPath }/resources/images/${memVo.getFilename()}" />
							 		</td>
							 		<td>
							 			<div>
							 				아이디 : ${memVo.getMem_id()}
							 			</div>
							 			<div>
							 				비밀번호 : ${memVo.getMem_pw()}
							 			</div>
							 			<div>
							 				이름 : ${memVo.getMem_name()}
							 			</div>
							 			<div>
							 				성별 : ${memVo.getMem_sex()}
							 			</div>
							 		</td>
							 		<td>
							 			<button class="btn btn-link" type="button">상세정보</button>
							 			<c:if test="${memVo.getMem_id() eq idVal}">
								 			<button class="logout btn btn-warning" type="button">로그아웃</button>
							 			</c:if>
							 		</td>
							 	</tr>
							 </c:forEach>
						 </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <script>
    	$(function(){
    		$(".logout").on("click", function(){
    			location.href = "ch07_test_signin.jsp";
    		});
    	});
    </script>

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

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

- http://localhost/ch07/ch07_test_signin.jsp

서버에 등록되지 않은 아이디나 비밀번호를 입력하면?
http://localhost/ch07/ch07_test_signin.jsp?fail=false 값으로 로그인 실패 메시지를 띄운다.

 

제대로 아이디와 비밀번호를 입력해 보았다.
유저 아이디로 환영 메시지를 띄운다.
로그아웃을 누르면 다시 메인 화면으로 돌아간다.
회원 가입을 하고 다시 로그인 해보자.
로그인 한 아이디와 일치하는 로그아웃 버튼만 활성화 된다.

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

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