TIL 0425

먼지·2024년 4월 25일
0

Today I Learned

목록 보기
48/89
post-thumbnail

[실습] 프로필 사진 - 강사님 코드

Profile Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>프로필 사진 업로드 폼</title>
<script type="text/javascript">
/* 미리보기 보여주기, 올라오면 submit 버튼 보여주기 */
	window.onload = function(){
	// 미리 보기 이미지 호출
	const image = document.getElementById('image');
	// 파일 선택시 이벤트 연결
	const file = document.getElementById('file');
	// 전송 버튼 호출
	const submit_btn = document.getElementById('submit_btn');
	
	file.onchange = function () {
		  if (!file.files[0]) {
			  image.src = '../images/face.png';
              return;
		  }
		// 선택한 이미지 읽기
		const reader = new FileReader();
		reader.readAsDataURL(file.files[0]);
		
		reader.onload = function(){
			image.src = reader.result;
			submit_btn.style.display = '';
		};
	};
};
</script>
</head>
<body>
<h2>Profile Image Upload</h2>
<img src="../images/face.png" width="200" height="200" id="image">
<form action="/ch03_JSP/profile" method="post" enctype="multipart/form-data">
	<input type="file" name="file" id="file" accept="image/gif,image/png,image/jpeg">
	<input type="submit" value="Profile Upload" id="submit_btn" style="display: none;">
</form>
</body>
</html>

Profile Servlet

package kr.web.ch05;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@MultipartConfig(
		maxFileSize = 1024 * 1024 * 5,
		maxRequestSize = 1024 * 1024 * 50
		)
@WebServlet("/profile")
public class UploadServlet3 extends HttpServlet {
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
//		컨텍스트 경로상의 파일 업로드 절대 경로 구하기
		String realFolder = request.getServletContext().getRealPath("/upload");
		
//		문서 타입 및 캐릭터셋 지정
		response.setContentType("text/html;charset=utf-8");
//		Post 방식으로 전송된 데이터 인코딩 타입 지정
		request.setCharacterEncoding("UTF-8");
//		HTML 출력을 위한 출력 스트림을 생성
		PrintWriter out = response.getWriter();
		try {
			Part part = request.getPart("file");
			String fileName = part.getSubmittedFileName();
			if(!fileName.isEmpty()) {
				part.write(realFolder + "/" + fileName);
				request.setAttribute("fileName", fileName);
			}
//			s04_profile.jsp로 forward
			RequestDispatcher dispatcher = request.getRequestDispatcher("/ch09_fileupload/s04_profile.jsp");
			dispatcher.forward(request, response);
		} catch(IllegalStateException e){	// 용량이 초과 되었을 때 해당 문구 출력
			out.println("용량 초과 : " + e.toString());
		}
	}

}

Profile JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>프로필 사진 업로드 처리</title>
</head>
<body>
<h2>저장된 프로필 사진</h2>
<img src="/ch03_JSP/upload/<%= request.getAttribute("fileName") %>" width="500">
</body>
</html>




JSP 와 DB 연동

JDBC

Java Database Connectivity
자바에서 DB 프로그래밍을 하기 위해 사용되는 API
JDBC API 사용 어플리케이션의 기본 구성

DB 연결하기

WEB-INF > lib > ojdbc8.jar 파일 넣어주기

Connection Test

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.SQLException"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>연동 테스트</title>
</head>
<body>
<%
	String driverName = "oracle.jdbc.OracleDriver";
	String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:xe";
	String dbId = "user01";
	String dbPass = "1234";
	
	Connection conn = null;
	
	try{
		//JDBC 수행 1단계 : Driver Load
		Class.forName(driverName);
		// JDBC 수행 2단계 : Connection 객체 생성
		conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);
		
		out.println("정상적으로 연결 되었습니다.");
	} catch(Exception e){
		e.printStackTrace();
	} finally{
		//자원 정리
		if(conn!=null) try{conn.close();} catch(SQLException e){}
	}
%>
</body>
</html>

[실습] 글 쓰기

Create tboard Table

create table tboard(
num number primary key,
name varchar2(30) not null,
title varchar2(150) not null,
passwd varchar2(10) not null,
content varchar2(4000) not null,
reg_date date not null
);
create sequence tboard_seq;

Script JS 작성

window.onload=function(){
	const myForm = document.getElementById('myForm');
	// 이벤트 연결
	myForm.onsubmit = function(){
		const items = document.querySelectorAll('input[type="text"], input[type="password"], textarea');
		for(let i = 0; i < items.length; i++){
			if(items[i].value.trim() == ''){
				const label = document.querySelector('label[for="' + items[i].id + '"]');
				alert(label.textContent + ' 항목은 필수 입력입니다.');
				items[i].value ='';
				items[i].focus();
				return false;
			}
		}		
	};
};

Style CSS 적용

@charset "UTF-8";

body{
    padding: 0;
    margin: 0;
}
.page-main{
    width: 800px;
    margin: 0 auto; /* 중앙 정렬 */
}
.result-display{
    width: 400px;
    height: 200px;
    margin: 50px auto;
    border: 1px solid #000;
    display: flex;
    align-items: center; /* 세로 정렬 */
    justify-content: center; /* 가로 정렬 */
}
.align-center{
    text-align: center;
}
.align-right{
    text-align: right;
}

/* 목록 */
table{
    width: 100%;
    border: 1px solid #000;
    border-collapse: collapse;
    margin-top: 5px;
}
table td, table th{
    border: 1px solid #000;
    padding: 5px;
}
/* 등록, 수정폼 */
form{
    width: 500px;
    margin: 0 auto;
    border: 1px solid #000;
    padding: 10px 10px 10px 30px;
}
ul{
    list-style: none;
}
label{
    width: 100px;
    float: left; /* 태그를 왼쪽으로 정렬 */
}

Insert Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 글 등록</title>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="page-main">
	<h2>글 쓰기</h2>
	<form action="insertTest.jsp" id="myForm" method="post">
		<ul>
			<li>
				<label for="name">이름</label>
				<input type="text" name="name" id="name" size="20" maxlength="10">
			</li>
			<li>
				<label for="title">제목</label>
				<input type="text" name="title" id="title" size="30" maxlength="10">
			</li>
			<li>
				<label for="passwd">비밀번호</label>
				<input type="password" name="passwd" id="passwd" size="20" maxlength="10">
			</li>
			<li>
				<label for="content">내용</label>
				<textarea rows="5" cols="40" name="content" id="content"></textarea>
			</li>
		</ul>
		<div class="align-center">
			<input type="submit" value="전송">
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</form>
</div>
</body>
</html>

Insert JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 쓰기 처리</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<%
/* Post 방식으로 전달된 데이터 인코딩 타입 지정*/
request.setCharacterEncoding("utf-8");

// 전송된 데이터 반환
String name = request.getParameter("name");
String title = request.getParameter("title");
String passwd = request.getParameter("passwd");
String content = request.getParameter("content");

//DB 연동하기
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;

try{
	// Connection 객체 반환
	conn = DBUtil.getConnection();
	// SQL문 작성
	sql = "INSERT INTO tboard (num, name, title, passwd, content, reg_date) VALUES (tboard_seq.nextval,?,?,?,?,SYSDATE)";
	
	//JDBC 수행 3단계 : pstmt 객체 생성
	pstmt = conn.prepareStatement(sql);
	// ?에 데이터 바인딩
	pstmt.setString(1,name);
	pstmt.setString(2,title);
	pstmt.setString(3,passwd);
	pstmt.setString(4,content);
	// JDBC 수행 4단계 : SQL문 실행
	pstmt.executeUpdate();
%>
	<div class="result-display">
		<div class="align-center">
		글을 등록했습니다.<p>
		<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
	
<%	
}catch(Exception e){
	
%>	
	
	<div class="result-display">
		<div class="align-center">
		오류가 발생하였습니다. 글 등록에 실패하였습니다.<p>
		<input type="button" value="글 쓰기" onclick="location.href='insertTestForm.jsp'">
		</div>
	</div>
	
<%	
	e.printStackTrace();
}finally{
	// 자원 정리
	DBUtil.executeClose(null, pstmt, conn);
}
%>
</body>
</html>

List Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.util.Date"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 목록</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body class="page-main">
	<h2>게시판 목록</h2>
	<div class="align-right">
		<input type="button" value="글쓰기" onclick="location.href='insertTestForm.jsp'">
	</div>
	<%
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try{
			// Connection 객체 반환
			conn = DBUtil.getConnection();
			
			//SQL 문 작성
			sql = "SELECT * FROM tboard ORDER BY num DESC";
			
			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			
			// JDBC 수행 4단계 : SQL문을 실행해서 테이블에 반영하고 결과 행을 resultset에 담아서 반환
			rs = pstmt.executeQuery();
%>
			<table>
				<tr>
					<th>글 번호</th>
					<th>제목</th>
					<th>작성자</th>
					<th>작성일</th>
				</tr>

<%
	while(rs.next()){
		int num = rs.getInt("num");
		String name = rs.getString("name");
		String title = rs.getString("title");
		Date reg_date = rs.getDate("reg_date");
		%>
		<tr>
			<td><%= num %></td>
			<td><a href="detailTest.jsp?num=<%= num %>"><%= title %></a></td>
			<td><%= name %></td>
			<td><%= reg_date %></td>
		</tr>
		
		<%
	}

%>
			</table>
<%
			
		}catch(Exception e){
			%>
			<div class="result-display">
				<span>오류 발생!</span>
			</div>
			<%
			e.printStackTrace();
		}finally{
			DBUtil.executeClose(rs, pstmt, conn);
		}
	
	%>
</body>
</html>

글 상세보기 Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.util.Date"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상세페이지</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
	<div class="page-main">
		<h2>글 상세 정보</h2>
		<%
		int num = Integer.parseInt(request.getParameter("num"));

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;

		try {
			// Connection 객체 반환
			conn = DBUtil.getConnection();

			//SQL 문 작성
			sql = "SELECT * FROM tboard WHERE num = ?";

			// JDBC 수행 3단계
			pstmt = conn.prepareStatement(sql);
			// ?에 데이터 바인딩
			pstmt.setInt(1, num);
			// JDBC 수행 4단계
			rs = pstmt.executeQuery();

			if(rs.next()){
				String name = rs.getString("name");
				String title = rs.getString("title");
				String content = rs.getString("content");
				Date reg_date = rs.getDate("reg_date");
			%>
			<ul>
				<li>글 번호 : <%= num %></li>
				<li>제목 : <%= title %></li>
				<li>작성자 : <%= name %></li>
				<li>작성일 : <%= reg_date %></li>
			</ul>
			<hr width="100%" size="1" noshade="noshade">
			<p>
				<%= content %>
			</p>
			<hr width="100%" size="1" noshade="noshade">
			<div class="align-right">
				<input type="button" value="수정" onclick="location.href='updateTestForm.jsp?num=<%=num%>'">
				<input type="button" value="삭제" onclick="location.href='deleteTestForm.jsp?num=<%=num%>'">
				<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
			</div>
<%
			} else{
%>

	<div class="result-display">
		<div class="align-center">
			글 상세 정보가 존재하지 않습니다.<p>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>

<%		
			}
			
		} catch (Exception e) {
%>

	<div class="result-display">
		<div class="align-center">
			오류가 발생하여 글 상세 정보를 불러오는데 실패하였습니다.<p>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>
	
<%		
			e.printStackTrace();
		} finally {
			DBUtil.executeClose(rs, pstmt, conn);
		}
		%>
	</div>

</body>
</html>

Update Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 글 수정</title>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="page-main">
	<h2>글 수정</h2>
<%
		int num = Integer.parseInt(request.getParameter("num"));

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		
		try{
			conn = DBUtil.getConnection();
			sql = "SELECT * FROM tboard WHERE num=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,num);
			
			rs = pstmt.executeQuery();
			if(rs.next()){
				String name = rs.getString("name");
				String title = rs.getString("title");
				String content = rs.getString("content");
%>
         	<form action="updateTest.jsp" id="myForm" method="post">
			<input type="hidden" name="num" value="<%= num %>">
		<ul>
			<li>
				<label for="name">이름</label>
				<input type="text" name="name" id="name" size="20" maxlength="10" value="<%= name %>">
			</li>
			<li>
				<label for="title">제목</label>
				<input type="text" name="title" id="title" size="30" maxlength="10" value="<%= title %>">
			</li>
			<li>
				<label for="passwd">비밀번호</label>
				<input type="password" name="passwd" id="passwd" size="20" maxlength="10">
			</li>
			<li>
				<label for="content">내용</label>
				<textarea rows="5" cols="40" name="content" id="content"><%= content %></textarea>
			</li>
		</ul>
		
		<div class="align-center">
			<input type="submit" value="전송">
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
		
	</form>
	
<%
			} else{
%>

		<div class="result-display">
			<div class="align-center">
				오류가 발생햇습니다. 수정할 글 정보 호출에 실패하였습니다.<p>
				<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
			</div>
		</div>

<%
			}
		} catch(Exception e) {
%>

		<div class="result-display">
			<div class="align-center">
				오류가 발생햇습니다. 수정할 글 정보 호출에 실패하였습니다.<p>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
			</div>
		</div>

<%
			e.printStackTrace();
		} finally{
			DBUtil.executeClose(rs, pstmt, conn);
		}
%>

</div>
</body>
</html>

Update JSP

<%@page import="java.sql.PreparedStatement"%>
<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 수정</title>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<%
	request.setCharacterEncoding("utf-8");

	int num = Integer.parseInt(request.getParameter("num"));
	String name = request.getParameter("name");
	String title = request.getParameter("title");
	String passwd = request.getParameter("passwd");
	String content = request.getParameter("content");
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	String sql = null;
	
	try{
		// Connection 객체 반환
		conn = DBUtil.getConnection();
		// SQL문 작성
		sql = "UPDATE tboard SET name=?,title=?,passwd=?,content=? WHERE num=?";
		// JDBC 수행 3단계
		pstmt = conn.prepareStatement(sql);
		// ?에 데이터 바인딩
		pstmt.setString(1,name);
		pstmt.setString(2,title);
		pstmt.setString(3,passwd);
		pstmt.setString(4,content);
		pstmt.setInt(5,num);
		
		// JDBC 수행 4단계 : SQL문 실행
		pstmt.executeUpdate();
%>
	
	<div class="result-display">
		<div class="align-center">
			글 수정이 완료되었습니다.<p>
			<input type="button" value="글상세" onclick="location.href='detailTest.jsp?num=<%= num %>'">
		</div>
	</div>
	
<%
	}catch(Exception e){
%>

		<div class="result-display">
			<div class="align-center">
				오류가 발생햇습니다. 수정할 글 정보 호출에 실패하였습니다.<p>
			<input type="button" value="목록" onclick="location.href='updateTestForm.jsp?num=<%= num%>'">
			</div>
		</div>
		
<%
		e.printStackTrace();
	}finally{
		DBUtil.executeClose(null, pstmt, conn);
	}
%>
</body>
</html>

Delete Form

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 삭제</title>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<%
int num = Integer.parseInt(request.getParameter("num"));
%>
<div class="page-main">
 <h2>글 삭제</h2>
 <p class="align-center">
 <span>정말 삭제하시겠습니까?</span>
 </p>
 <form action="deleteTest.jsp">
 	<input type="hidden" name="num" value="<%= num%>">
 	<div class="align-center">
 		<input type="submit" value="삭제">
 		<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
 	</div>
 </form>
</div>
</body>
</html>

Delete JSP

<%@ page import="kr.util.DBUtil"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 삭제 처리</title>
<link rel="stylesheet" href="../css/style.css" type="text/css">
</head>
<body>

<%
	// POST 방식으로 전송된 데이터 인코딩 타입 지정
	request.setCharacterEncoding("UTF-8");

	// 전송된 데이터 반환
	int num = Integer.parseInt(request.getParameter("num"));

	Connection conn = null;
	PreparedStatement pstmt = null;
	String sql = null;
	try {
		// Connection 객체 반환
		conn = DBUtil.getConnection();
		// SQL문 작성
		sql = "DELETE FROM tboard WHERE num=?";
		//JDBC 수행 3단계
		pstmt = conn.prepareStatement(sql);
		// ?에 데이터 바인딩
		pstmt.setInt(1, num);
		//JDBC 수행 4단계 : SQL문 실행
		pstmt.executeUpdate();
%>

	<div class="result-display">
		<div class="align-center">
			글 삭제가 완료되었습니다.<p>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>


<%
	} catch (Exception e) {
%>

	<div class="result-display">
		<div class="align-center">
			오류가 발생하였습니다. 글 삭제에 실패하였습니다.<p>
			<input type="button" value="목록" onclick="location.href='selectTest.jsp'">
		</div>
	</div>

<%
		e.printStackTrace();
	} finally {
		DBUtil.executeClose(null, pstmt, conn);
	}
%>
</body>
</html>
profile
Lucky Things🍀

0개의 댓글