전체구성
메이븐으로 pom.xml 의 build태그 밖에 cos,connector-j 추가해준다
jstl 사용시 jstl,taglibs(standard)도 같이 추가해준다
<dependencies>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jfinal/cos -->
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>cos</artifactId>
<version>2020.4</version>
</dependency>
</dependencies>
Dbconn.java
package com.koreait.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Dbconn {
private static Connection conn; //메모리에 계속 살아있을것임
public static Connection getConnection() throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://localhost/aidev?useSSL=false&allowPublicKeyRetrieval=true";
String uid = "root";
String upw = "1111";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, uid, upw);
return conn;
}
}
더보기
로그인
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션으로 구현한 로그인</title>
</head>
<body>
<h2> 세션으로 구현한 로그인</h2>
<%
if(userid == null){
%>
<form method="post" action="./login_ok.jsp">
<p>아이디: <input type = "text" name = "userid"></p>
<p>비밀번호: <input type = "password" name = "userpw"></p>
<p><button>로그인</button></p>
</form>
<p>아직 회원이 아니신가요? <a href="./member.jsp">회원가입</a></p>
<%
} else{
%>
<h3><%=userid%>님 환영합니다 !!!!</h3>
<p><a href="./logout.jsp"> 로그아웃 </a> | <a href='./info.jsp'>정보수정</a> | <a href="./board/list.jsp"> 게시판</a></p>
<%
}
%>
</body>
</html>
login_ok.jsp
<%@ page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="java.sql.*" %>
<%@ page import = "com.koreait.db.Dbconn" %>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw"); //name값으로 인
Connection conn = null;
PreparedStatement pstmt;
ResultSet rs = null;
try{
conn = Dbconn.getConnection();
if(conn != null){
String sql = "select mem_userid, mem_username from tb_member where mem_userid=? and mem_userpw=sha2(?,256)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,userid);
pstmt.setString(2,userpw);
rs = pstmt.executeQuery();
if(rs.next()){
session.setAttribute("userid",userid);
session.setAttribute("name",rs.getString("mem_username"));
%>
<script>
alert('로그인 되었습니다');
location.href="login.jsp" //refresh가됨 새로고침이되는것임
</script>
<%
}else{
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요');
history.back(); // 캐쉬가남음 캐쉬에 있는 정보를 가져다가 앞으로갓다가 뒤로갓다가 할수있는것이라서
</script>
<%
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
%>
<script>
alert('logout되었습니다');
location.href='login.jsp';
</script>
회원가입
member.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>회원가입</title>
<script defer src="./js/regist.js"></script>
<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
function sample6_execDaumPostcode() {
new daum.Postcode({
oncomplete: function(data) {
// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수
//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample6_extraAddress").value = extraAddr;
} else {
document.getElementById("sample6_extraAddress").value = '';
}
// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample6_postcode').value = data.zonecode;
document.getElementById("sample6_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample6_detailAddress").focus();
}
}).open();
}
</script>
</head>
<body>
<h2>회원가입</h2>
<form action="./member_ok.jsp" name="regform" id="regform" method="post" onsubmit="return sendit()">
<!-- onsubmit 값이 false이면 submit안함! -->
<input type="hidden" name="isIdCheck" id="isIdCheck" value="n">
<p>아이디: <input type="text" name="userid" id="userid" maxlength="20" onkeydown="idModify()">
<input type="button" id="btnIdCheck" value= "중복체크" onclick="clickBtn()">
</p>
<p id = "checkmsg"></p>
<p>비밀번호: <input type="text" name="userpw" id="userpw" maxlength="20" ></p>
<p>비밀번호 확인: <input type="text" name="userpw_re" id="userpw_re" maxlength="20" ></p>
<p>이름: <input type="text" name="name" id="name"></p>
<p>휴대폰번호: <input type="text" name="hp" id="hp"></p>
<p>이메일: <input type="text" name="email" id="email"></p>
<p>성별: <label>남자<input type="radio" name="gender" value="남자" checked></label> <label>여자<input type="radio" name="gender" value="여자"></label></p>
<p>취미: <label>등산<input type="checkbox" name="hobby" value="등산"></label>
<label>게임<input type="checkbox" name="hobby" value="게임"></label>
<label>운동<input type="checkbox" name="hobby" value="운동"></label>
<label>드라이브<input type="checkbox" name="hobby" value="드라이브"></label>
<label>독서<input type="checkbox" name="hobby" value="독서"></label></p>
<p>주민등록번호<input type="text" name="ssn1"><input type="text" name="ssn2">
<p>우편번호: <input type="text" id="sample6_postcode" name="zipcode" maxlength="5"><button type="button" onclick="sample6_execDaumPostcode()">검색</button></p>
<p>주소: <input type="text" name="address1" id="sample6_address"></p>
<p>상세주소: <input type="text" name="address2" id="sample6_detailAddress"></p>
<p>참고항목: <input type="text" name="address3" id="sample6_extraAddress"></p>
<p><button>가입완료</button> <button type="reset">다시작성</button> </p>
</form>
<p>이미 회원이신가요? <a href="login.jsp">로그인</a></p>
</body>
</html>
member_ok.jsp
<%@page import="com.koreait.db.Dbconn"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ page import="java.sql.*" %>
<%
request.setCharacterEncoding("UTF-8");
Connection conn = null;
PreparedStatement pstmt = null;
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
String name = request.getParameter("name");
String hp = request.getParameter("hp");
String email = request.getParameter("email");
String gender = request.getParameter("gender");
String[] hobby = request.getParameterValues("hobby");
String ssn1 = request.getParameter("ssn1");
String ssn2 = request.getParameter("ssn2");
String zipcode = request.getParameter("zipcode");
String address1 = request.getParameter("address1");
String address2 = request.getParameter("address2");
String address3 = request.getParameter("address3");
try{
conn = Dbconn.getConnection();
if(conn != null){
/* System.out.println("DB연결 성공!"); */
String sql = "insert into tb_member(mem_userid, mem_userpw, mem_username, mem_hp, mem_email, mem_hobby, mem_ssn1, mem_ssn2, mem_zipcode, mem_address1, mem_address2,mem_address3, mem_gender) values(?,sha2(?,256),?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userid);
pstmt.setString(2, userpw);
pstmt.setString(3, name);
pstmt.setString(4, hp);
pstmt.setString(5, email);
String hobbystr = "";
for(int i=0; i<hobby.length; i++){
hobbystr = hobbystr + hobby[i] + " ";
}
pstmt.setString(6, hobbystr);
pstmt.setString(7, ssn1);
pstmt.setString(8, ssn2);
pstmt.setString(9, zipcode);
pstmt.setString(10, address1);
pstmt.setString(11, address2);
pstmt.setString(12, address3);
pstmt.setString(13, gender);
pstmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
%>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입 완료</title>
</head>
<body>
<h2>회원가입 완료</h2>
<p><%=name%>(<%=userid%>)님 회원가입이 완료되었습니다</p>
<p><a href="login.jsp">로그인하러가기</a></p>
</body>
</html>
regist.js
function sendit(){
const userid = document.getElementById('userid');
const isIdCheck = document.getElementById('isIdCheck');
const userpw = document.getElementById('userpw');
const userpw_re = document.getElementById('userpw_re');
const name = document.getElementById('name');
const hp = document.getElementById('hp');
const email = document.getElementById('email');
const hobby = document.getElementsByName('hobby');
// 정규 표현식
const expIdText = /^[A-Za-z\d]{4,20}$/;
const expNameText = /[가-힣]+$/;
const exeHpText = /^\d{3}-\d{3,4}-\d{4}$/;
const expEmailText = /^[A-Za-z0-9\-\.]+@[A-Za-z0-9\-\.]+\.[A-Za-z0-9]+$/;
const expPwText =/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}/;
if(userid.value ==''){
alert('아이디를 입력하세요');
userid.focus();
return false;
}
if(!expIdText.test(userid.value)){
alert('아이디는 4자 이상 20자 이하의 대소문자로 시작하는 조합입니다')
userid.focus();
return false;
}
if(isIdCheck.value == 'n'){
alert('아이디 중복체크 버튼을 눌러주세요');
return false;
}
if(userpw.value ==''){
alert('비밀번호를 입력하세요');
userpw.focus();
return false;
}
if(!expPwText.test(userpw.value)){
alert('비밀번호 형식을 확인하세요\n소문자,대문자,숫자,특수문자 1개씩 꼭 입력해야합니다');
userpw.focus();
return false;
}
if(userpw.value != userpw_re.value){
alert('비밀번호와 비밀번호 확인의 값이 다릅니다')
userpw_re.focus();
return false;
}
if(name.value ==''){
alert('이름을 입력하세요');
name.focus();
return false;
}
if(!expNameText.test(name.value)){
alert('이름은 한글로 입력하세요');
name.focus();
return false;
}
if(!exeHpText.test(hp.value)){
alert('휴대폰번호 형식을 확인하세요\n하이픈(-)을 포함해야합니다');
hp.focus();
return false;
}
if(!expEmailText.test(email.value)){
alert('이메일 형식을 확인하세요')
email.focus();
return false;
}
let count = 0;
for(let i in hobby){
if(hobby[i].checked){
count++;
}
}
if(count == 0){
alert('취미는 적어도 하나 이상 선택하세요');
return false;
}
return true;
//return true
//return false
}
function clickBtn(){
const isIdCheck = document.getElementById('isIdCheck');
const xhr = new XMLHttpRequest();
const userid = document.getElementById('userid').value;
xhr.open('get','idcheck.jsp?userid=' + userid, true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
const result = xhr.responseText;
if(result.trim() == "ok"){
document.getElementById('checkmsg').innerHTML = "<b style='color:blue'>사용할 수 있는 아이디</b>";
isIdCheck.value = 'y';
}else{
document.getElementById('checkmsg').innerHTML = "<b style='color:red'>사용할 수 없는 아이디</b>";
}
}
}
}
function idModify(){
const isIdCheck = document.getElementById('isIdCheck');
isIdCheck.value = 'n';
document.getElementById('checkmsg').innerHTML="";
}
idcheck.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.koreait.db.Dbconn"%>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs =null;
String userid= request.getParameter("userid");
try{
conn = Dbconn.getConnection();
if(conn != null){
String sql = "select mem_userid from tb_member where mem_userid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,userid);
rs = pstmt.executeQuery();
if(rs.next()){
out.print("no"); //가입을 할수 없는 경우
}else{
out.print("ok"); //가입을 할수 있는 경우
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
세션체크
로그인 이후 부터는 보안상 항상 세션체크가 필요하다
<%@ include file = "./include/sessioncheck.jsp"%>
로그인 이후에 들어가는 페이지 상단에 include 시켜줘야함!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
if(session.getAttribute("userid") == null){
response.sendRedirect("../login.jsp");
return;
}
%>
회원정보수정
info.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.koreait.db.Dbconn" %>
<%@ include file = "./include/sessioncheck.jsp"%>
<%!
public static boolean compareHobby(String[] arr, String item){
for(String i : arr){
if(i.equals(item)){
return true;
}
}
return false;
}
%>
<%
// String idx = (String)session.getAttribute("idx")//idx를 사용하여 검색하면 속도가 유리(인덱싱되어있기때문)
String userid = (String)session.getAttribute("userid");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String mem_username = "";
String mem_hp = "";
String mem_email = "";
String[] hobbyArr = null;
String mem_ssn1 = "";
String mem_ssn2 = "";
String mem_zipcode = "";
String mem_address1 = "";
String mem_address2 = "";
String mem_address3 = "";
String mem_gender = "";
try{
conn = Dbconn.getConnection();
if(conn != null){
//*(에스터리스크)절대 사용하지 말것!
String sql = "select * from tb_member where mem_userid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userid);
rs = pstmt.executeQuery();
if(rs.next()){
mem_username = rs.getString("mem_username");
mem_hp = rs.getString("mem_hp");
mem_email = rs.getString("mem_email");
hobbyArr = rs.getString("mem_hobby").split(" ");
mem_ssn1 = rs.getString("mem_ssn1");
mem_ssn2 = rs.getString("mem_ssn2");
mem_zipcode = rs.getString("mem_zipcode");
mem_address1 = rs.getString("mem_address1");
mem_address2 = rs.getString("mem_address2");
mem_address3 = rs.getString("mem_address3");
mem_gender = rs.getString("mem_gender");
}
}
}catch(Exception e){
}
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>정보수정</title>
<script defer src="./js/info.js"></script>
<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
function sample6_execDaumPostcode() {
new daum.Postcode({
oncomplete: function(data) {
// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수
//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample6_extraAddress").value = extraAddr;
} else {
document.getElementById("sample6_extraAddress").value = '';
}
// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample6_postcode').value = data.zonecode;
document.getElementById("sample6_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample6_detailAddress").focus();
}
}).open();
}
</script>
</head>
<body>
<h2>정보수정</h2>
<form action="./info_ok.jsp" name="regform" id="regform" method="post" onsubmit="return sendit()">
<p>아이디: <%=userid%></p>
<p>비밀번호: <input type="password" name="userpw" id="userpw" maxlength="20" ></p>
<p>비밀번호 확인: <input type="password" name="userpw_re" id="userpw_re" maxlength="20" ></p>
<p>이름: <input type="text" name="name" id="name" value="<%=mem_username%>"></p>
<p>휴대폰번호: <input type="text" name="hp" id="hp" value="<%=mem_hp%>"></p>
<p>이메일: <input type="text" name="email" id="email" value="<%=mem_email%>"></p>
<p>성별:
<label>남자<input type="radio" name="gender" value="남자"
<% if(mem_gender.equals("남자"))out.print("checked"); %>></label>
<label>여자<input type="radio" name="gender" value="여자"
<% if(mem_gender.equals("여자"))out.print("checked"); %>></label></p>
<p>취미:
<label>등산<input type="checkbox" name="hobby" value="등산"
<%
if(compareHobby(hobbyArr, "등산")) out.print("checked"); //함수를 써서 사용 가
%>></label>
<label>게임<input type="checkbox" name="hobby" value="게임"
<%
for(int i=0;i<hobbyArr.length;i++){
if(hobbyArr[i].equals("게임"))out.print("checked");
}
%>></label>
<label>운동<input type="checkbox" name="hobby" value="운동"
<%
for(int i=0;i<hobbyArr.length;i++){
if(hobbyArr[i].equals("운동"))out.print("checked");
}
%>></label>
<label>드라이브<input type="checkbox" name="hobby" value="드라이브"
<%
for(int i=0;i<hobbyArr.length;i++){
if(hobbyArr[i].equals("드라이브"))out.print("checked");
}
%>></label>
<label>독서<input type="checkbox" name="hobby" value="독서"
<%
for(int i=0;i<hobbyArr.length;i++){
if(hobbyArr[i].equals("독서"))out.print("checked");
}
%>></label>
</p>
<p>주민등록번호<input type="text" name="ssn1" value="<%=mem_ssn1%>"><input type="text" name="ssn2" value="<%=mem_ssn2%>">
<p>우편번호: <input type="text" id="sample6_postcode" name="zipcode" maxlength="5" value="<%=mem_zipcode%>"><button type="button" onclick="sample6_execDaumPostcode()">검색</button></p>
<p>주소: <input type="text" name="address1" id="sample6_address" value="<%=mem_address1%>"></p>
<p>상세주소: <input type="text" name="address2" id="sample6_detailAddress" value="<%=mem_address2%>"></p>
<p>참고항목: <input type="text" name="address3" id="sample6_extraAddress" value="<%=mem_address3%>"></p>
<p><button>수정완료</button> <button type="reset">다시작성</button><button type="button"onclick="location.href='./login.jsp'">돌아가기</button> </p>
</form>
</body>
</html>
info_ok.jsp
<%@ page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="java.sql.*" %>
<%@ page import = "com.koreait.db.Dbconn" %>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw"); //name값으로 인
Connection conn = null;
PreparedStatement pstmt;
ResultSet rs = null;
try{
conn = Dbconn.getConnection();
if(conn != null){
String sql = "select mem_userid, mem_username from tb_member where mem_userid=? and mem_userpw=sha2(?,256)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,userid);
pstmt.setString(2,userpw);
rs = pstmt.executeQuery();
if(rs.next()){
session.setAttribute("userid",userid);
session.setAttribute("name",rs.getString("mem_username"));
%>
<script>
alert('로그인 되었습니다');
location.href="login.jsp" //refresh가됨 새로고침이되는것임
</script>
<%
}else{
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요');
history.back(); // 캐쉬가남음 캐쉬에 있는 정보를 가져다가 앞으로갓다가 뒤로갓다가 할수있는것이라서
</script>
<%
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
info.js
function sendit(){
const userpw = document.getElementById('userpw');
const userpw_re = document.getElementById('userpw_re');
const name = document.getElementById('name');
const hp = document.getElementById('hp');
const email = document.getElementById('email');
const hobby = document.getElementsByName('hobby');
// 정규 표현식
const expNameText = /[가-힣]+$/;
const exeHpText = /^\d{3}-\d{3,4}-\d{4}$/;
const expEmailText = /^[A-Za-z0-9\-\.]+@[A-Za-z0-9\-\.]+\.[A-Za-z0-9]+$/;
const expPwText =/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}/;
if(userpw.value ==''){
alert('비밀번호를 입력하세요');
userpw.focus();
return false;
}
if(!expPwText.test(userpw.value)){
alert('비밀번호 형식을 확인하세요\n소문자,대문자,숫자,특수문자 1개씩 꼭 입력해야합니다');
userpw.focus();
return false;
}
if(userpw.value != userpw_re.value){
alert('비밀번호와 비밀번호 확인의 값이 다릅니다')
userpw_re.focus();
return false;
}
if(name.value ==''){
alert('이름을 입력하세요');
name.focus();
return false;
}
if(!expNameText.test(name.value)){
alert('이름은 한글로 입력하세요');
name.focus();
return false;
}
if(!exeHpText.test(hp.value)){
alert('휴대폰번호 형식을 확인하세요\n하이픈(-)을 포함해야합니다');
hp.focus();
return false;
}
if(!expEmailText.test(email.value)){
alert('이메일 형식을 확인하세요')
email.focus();
return false;
}
let count = 0;
for(let i in hobby){
if(hobby[i].checked){
count++;
}
}
if(count == 0){
alert('취미는 적어도 하나 이상 선택하세요');
return false;
}
return true;
//return true
//return false
}
게시판 목록
list.jsp
<%@page import="java.util.Set"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/sessioncheck.jsp"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*"%>
<%
/*
1 0 9
2 10 19
n (n-1)*10 (n-1)*10+9
*/
String pageNum = request.getParameter("pageNum");
if (pageNum==null) {
pageNum = "1";
}
int pagePerCount = 10;
int pageEnd = 0;
int index = 0 + ((Integer.parseInt(pageNum) - 1) * 10);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table {
width: 800px;
border: 1px solid black;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
}
.bottom {
}
.totalnum {
margin-left: 600px;
}
</style>
</head>
<body>
<h2>리스트</h2>
<table>
<tr>
<th>번호</th>
<th>제목</th>
<th>글쓴이</th>
<th>조회수</th>
<th>날짜</th>
<th>좋아요</th>
</tr>
<%
request.setCharacterEncoding("UTF-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String userid = (String) session.getAttribute("userid");
String name = (String) session.getAttribute("name");
String title = request.getParameter("b_title");
String content = request.getParameter("b_content");
String b_idx = "";
String b_title = "";
String b_userid = "";
String b_hit = "";
String b_regdate = "";
String b_like = "";
String b_name = "";
String cnt = "";
String b_filename="";
int total_cnt = 0;
String nnn = "";
try {
conn = Dbconn.getConnection();
if (conn != null) {
/* System.out.println("DB연결 성공!"); */
String sql = "select * from tb_fileboard order by b_idx desc LIMIT ?, ?";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setInt(1, (Integer.parseInt(pageNum) - 1) * pagePerCount);
pstmt.setInt(2, pagePerCount);
rs = pstmt.executeQuery();
while (rs.next()) {
b_idx = rs.getString("b_idx");
b_title = rs.getString("b_title");
b_userid = rs.getString("b_userid");
b_hit = rs.getString("b_hit");
b_regdate = rs.getString("b_regdate");
b_like = rs.getString("b_like");
b_name = rs.getString("b_name");
b_filename = rs.getString("b_filename");
%>
<tr>
<td>
<%index += 1;%> <%=index%></td>
<td><a href="./view.jsp?b_idx=<%=b_idx%>"><%=b_title%> <%
try {
conn = Dbconn.getConnection();
if (conn != null) {
ResultSet re_rs = null;
/* System.out.println("DB연결 성공!"); */
String re_sql = "select count(*) as cnt from tb_filereply where re_boardidx=?;";
pstmt = conn.prepareStatement(re_sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, b_idx);
re_rs = pstmt.executeQuery();
re_rs.next();
cnt = re_rs.getString("cnt");
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<!-- 댓글갯수 -->
<%
if (cnt.equals("0")) {
%> <%
} else {
%> [<%=cnt%>] <%
}
%>
<!-- 3일이내 올라온 글들은 new -->
<%
try {
conn = Dbconn.getConnection();
if (conn != null) {
ResultSet re_rs = null;
/* System.out.println("DB연결 성공!"); */
String re_sql = "select b_idx from tb_fileboard where b_regdate >= (select date_sub(now(),interval 3 day)) and b_idx=?";
pstmt = conn.prepareStatement(re_sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, b_idx);
re_rs = pstmt.executeQuery(); // 값이 존재하지 않으면 에러가니면서 catch로
re_rs.next();
nnn = re_rs.getString("b_idx");
}
} catch (Exception e) {
nnn = null;
e.printStackTrace();
}
if (nnn != null) {
%> <img alt="" style="width: 20px;"
src="./new.png"><%}
%><!-- 첨부파일있는놈은 첨부파일 아이콘
--><%
if (b_filename != null && !b_filename.equals("null")){
%><img alt="" style="width: 20px;"
src="./attach.png">
<%
}
%> </a></td>
<td><%=b_userid%>(<%=b_name%>)</td>
<td><%=b_hit%></td>
<td><%=b_regdate%></td>
<td><%=b_like%></td>
</tr>
<%
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<%
try {
conn = Dbconn.getConnection();
if (conn != null) {
ResultSet re_rs = null;
/* System.out.println("DB연결 성공!"); */
String re_sql = "select count(*) as cnt from tb_fileboard";
pstmt = conn.prepareStatement(re_sql); //컴파일하고 나서 set 설정해줘야함!
re_rs = pstmt.executeQuery();
while (re_rs.next()) {
total_cnt = re_rs.getInt("cnt"); //전체 게시글
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td colspan="6">
<%
if (total_cnt % pagePerCount == 0)
pageEnd = total_cnt / pagePerCount;
else {
pageEnd = (total_cnt / pagePerCount) + 1;
}
for (int i = 1; i <= pageEnd; i++) {
%> <a href='./list.jsp?pageNum=<%=i%>'> [<%=i%>]
</a> <%
}
%>
</tr>
</td>
</table>
<p class="bottom">
<a href='write.jsp'> 글쓰기</a> <a href="../login.jsp">돌아가기</a> <span
class="totalnum">글 전체수 : <%=total_cnt%>개
</span>
</p>
</body>
</html>
글보기
view.jsp 글보기 페이지
<%@page import="java.io.Console"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/sessioncheck.jsp"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.koreait.FileService" %>
<%
request.setCharacterEncoding("UTF-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String num = request.getParameter("b_idx");
String userid = (String) session.getAttribute("userid");
String name = (String) session.getAttribute("name");
String b_idx = "";
String b_title = "";
String b_userid = "";
String b_hit = "";
String b_regdate = "";
String b_like = "";
String b_name = "";
String b_content = "";
String b_filename ="";
String b_filepath ="";
String re_idx = "";
String re_userid = "";
String re_name = "";
String re_content = "";
String re_regdate = "";
String re_boardidx = "";
boolean visited =false;
//조회수 올리기
try {
conn = Dbconn.getConnection();
if (conn != null) {
/* 먼저 조회한적있는지 체크 */
String sql = "select * from tb_filevisited where v_boardidx=? and v_userid=? ";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num);
pstmt.setString(2, userid);
rs = pstmt.executeQuery();
while(rs.next()) {visited=true;}
/* 조회한적있다면 */
if(visited){
sql = "select * from tb_fileboard where b_idx=? ";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num);
rs = pstmt.executeQuery();
rs.next();
b_idx = rs.getString("b_idx");
b_title = rs.getString("b_title");
b_userid = rs.getString("b_userid");
b_hit = rs.getString("b_hit");
b_regdate = rs.getString("b_regdate");
b_like = rs.getString("b_like");
b_name = rs.getString("b_name");
b_content = rs.getString("b_content");
}else{
/* 조회한적없다면 */
//tb_visited테이블에 등
sql = "insert into tb_filevisited(v_boardidx,v_userid) values(?,?)";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num);
pstmt.setString(2, userid);
pstmt.executeUpdate();
sql = "update tb_fileboard set b_hit=b_hit+1 where b_idx=? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.executeUpdate();
sql = "select * from tb_fileboard where b_idx=? ";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num);
rs = pstmt.executeQuery();
rs.next();
b_idx = rs.getString("b_idx");
b_title = rs.getString("b_title");
b_userid = rs.getString("b_userid");
b_hit = rs.getString("b_hit");
b_regdate = rs.getString("b_regdate");
b_like = rs.getString("b_like");
b_name = rs.getString("b_name");
b_content = rs.getString("b_content");
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글보기</title>
<script>
function like(){
/* 하트버튼의 속성값들을변경하여 하트전환 */
const isHeart = document.querySelector("img[title=on]");
if(isHeart){
document.getElementById('heart').setAttribute('src', 'https://www.iconpacks.net/icons/2/free-heart-icon-3510-thumb.png')
document.getElementById('heart').setAttribute('title', 'off')
}else{
document.getElementById('heart').setAttribute('src', 'https://cdn-icons-png.flaticon.com/512/105/105220.png')
document.getElementById('heart').setAttribute('title', 'on')
}
const xhr = new XMLHttpRequest(); //0번
xhr.open('get', 'like.jsp?idx=<%=num%>&userid=<%=userid%>',true); //1번
xhr.send(); //2번 ->3번(불러오는 로딩) ->4번(다불러오면 완료상태로 변경!)
// XMLHttpRequest.DONE -> readyState: 4)
xhr.onreadystatechange = function(){
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
document.getElementById('likenum').innerText= xhr.responseText.trim();
}
}
}
function del(idx){
const yn = confirm('게시글을 삭제하시겠습니까?');
if(yn) location.href='./delete_ok.jsp?b_idx='+idx;
}
function replyDel(re_idx,b_idx){
const yn = confirm('해당댓글을 삭제하시겠습니까?');
if(yn)location.href= './reply_del_ok.jsp?re_idx='+re_idx + "&b_idx=" + b_idx;
}
</script>
<style type="text/css">
table {
width: 800px;
border: 1px solid black;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
}
#img{
display:none;}
#imgtitle:hover{
font-weight: 600;
}
#imgtitle:hover #img{
display:block;
position:fixed;
background-color: red;
}
</style>
</head>
<body>
<h2>글보기</h2>
<table>
<tr>
<th>제목
<td><%=b_title%></td>
</tr>
<tr>
<th>날짜
<td><%=b_regdate%></td>
</tr>
<tr>
<th>작성자
<td><%=b_name%></td>
</tr>
<tr>
<th>조회수
<td><%=b_hit%></td>
</tr>
<tr>
<th>좋아요
<td id="likenum"><%=b_like%></td>
</tr>
<tr>
<th>내용
<td><%=b_content%></td>
</tr>
<%
try{
conn = Dbconn.getConnection();
String sql="";
Boolean isLike=false;
if(conn != null){
/* System.out.println("DB연결 성공!"); */
sql = "select * from tb_fileboard where b_idx = ? and b_userid = ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.setString(2, userid);
rs = pstmt.executeQuery();
while(rs.next()){
b_filename = rs.getString("b_filename");
b_filepath = rs.getString("b_filepath");
}
if(!b_filename.equals("null")){
%>
<tr>
<th>첨부파일
<td><span href="" id="imgtitle"><%=b_filename%><img id="img" src="./upload<%=b_filepath%>"></span></td>
</tr>
<%
}
%>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
<tr>
<td colspan="2">
<%
if (b_userid.equals(userid)) {
%> <input type="button" value="수정"
onclick="location.href='edit.jsp?b_idx=<%=b_idx%>&b_filename=<%=b_filename%>&b_filepath=<%=b_filepath%>'"> <%-- <input type="button" value="삭제" onclick="location.href='delete_ok.jsp?b_idx=<%=b_idx%>'"> --%>
<input type="button" value="삭제" onclick="del(<%=b_idx%>)"> <%
}
%> <input type="button" value="리스트" onclick="location.href='./list.jsp'">
<!-- <input type="button" id="like" value="좋아요" onclick="like()">
-->
<%
boolean isLike = false;
String sql="";
try{
conn = Dbconn.getConnection();
if(conn != null){
/* System.out.println("DB연결 성공!"); */
sql = "select * from tb_filelike where l_boardidx = ? and l_userid = ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.setString(2, userid);
rs = pstmt.executeQuery();
while(rs.next()){
isLike = true;
}
if(isLike){
%>
<button onclick="like()">
<img title="on" value="true" id="heart" src="https://cdn-icons-png.flaticon.com/512/105/105220.png" width="20px" id="like" />
</button>
<%
}else{%>
<button onclick="like()">
<img title="off" value="false" id="heart" src="https://www.iconpacks.net/icons/2/free-heart-icon-3510-thumb.png" width="20px" id="notlike" />
</button>
<%
}
%>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</td>
</tr>
</table>
<hr>
<form method="post" action="../re_write_ok">
<input type="hidden" name="b_username" value=<%=name%>>
<input type="hidden" name="b_userid" value=<%=userid%>>
<input type="hidden" name="b_idx" value="<%=b_idx%>">
<p><%=userid%>(<%=b_name%>):<input type="text" name="re_content">
<button>확인</button>
</p>
</form>
<hr>
<%
conn = Dbconn.getConnection();
sql = "";
if (conn != null) {
sql = "select * from tb_filereply where re_boardidx=? order by re_idx desc;";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num);
rs = pstmt.executeQuery();
}
while (rs.next()) {
re_idx = rs.getString("re_idx");
re_userid = rs.getString("re_userid");
re_name = rs.getString("re_name");
re_content = rs.getString("re_content");
re_regdate = rs.getString("re_regdate");
re_boardidx = rs.getString("re_boardidx");
if(userid.equals(re_userid)){
%>
<p>
☻ <%=re_name%>:
<%=re_content%>(<%=re_regdate%>)
<input type="button" value="삭제" onclick="replyDel('<%=re_idx%>','<%=b_idx%>')">
</p>
<%
}else{
%>
<p>
☻ <%=re_name%>:
<%=re_content%>(<%=re_regdate%>)
</p>
<%
}
}
%>
</body>
</html>
<%
} catch (Exception e) {
e.printStackTrace();
}
%>
like.jsp 좋아요기능
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*" %>
<%
String num = request.getParameter("idx");
String userid = request.getParameter("userid");
String likenum ="";
boolean isLike = false;
request.setCharacterEncoding("UTF-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql="";
try{
conn = Dbconn.getConnection();
if(conn != null){
/* System.out.println("DB연결 성공!"); */
sql = "select * from tb_filelike where l_boardidx = ? and l_userid = ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.setString(2, userid);
rs = pstmt.executeQuery();
while(rs.next()){
isLike = true;
}
if(isLike){
String hitminus = "update tb_fileboard set b_like=b_like-1 where b_idx=? ";
pstmt = conn.prepareStatement(hitminus);
pstmt.setString(1, num );
pstmt.executeUpdate();
hitminus = "delete from tb_filelike where l_boardidx = ? and l_userid = ? ";
pstmt = conn.prepareStatement(hitminus);
pstmt.setString(1, num );
pstmt.setString(2, userid);
pstmt.executeUpdate();
sql = "select * from tb_fileboard where b_idx=? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num );
rs = pstmt.executeQuery();
while(rs.next()){
likenum=rs.getString("b_like");
out.print(likenum);}
}else{
String hitplus = "update tb_fileboard set b_like=b_like+1 where b_idx=? ";
pstmt = conn.prepareStatement(hitplus);
pstmt.setString(1, num );
pstmt.executeUpdate();
hitplus = "insert into tb_filelike(l_boardidx,l_userid) values(?,?)";
pstmt = conn.prepareStatement(hitplus);
pstmt.setString(1, num );
pstmt.setString(2, userid);
pstmt.executeUpdate();
sql = "select * from tb_fileboard where b_idx=? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num );
rs = pstmt.executeQuery();
while(rs.next()){
likenum=rs.getString("b_like");
out.print(likenum);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
reply_del_ok.jsp 댓글삭제기능
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@ page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*" %>
<%
request.setCharacterEncoding("UTF-8");
String b_idx = request.getParameter("b_idx");
String re_idx = request.getParameter("re_idx");
String re_userid = request.getParameter("re_userid");
String userid = (String)session.getAttribute("userid");
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = Dbconn.getConnection();
if(conn != null){
String sql = "delete from tb_filereply where re_idx =? and re_userid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, re_idx);
pstmt.setString(2,userid);
pstmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
%>
<script>
alert('삭제되었습니다');
location.href= 'view.jsp?b_idx=<%=b_idx%>';
</script>
delete_ok.jsp 게시글삭제기능
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@ page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*" %>
<%
request.setCharacterEncoding("UTF-8");
String b_idx = request.getParameter("b_idx");
String userid = (String)session.getAttribute("userid");
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = Dbconn.getConnection();
if(conn != null){
String sql = "delete from tb_fileboard where b_idx =? and b_userid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, b_idx);
pstmt.setString(2,userid);
pstmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
%>
<script>
alert('삭제되었습니다');
location.href= 'list.jsp';
</script>
글쓰기(첨부파일포함가능)
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%
String userid = (String)session.getAttribute("userid");
String name = (String)session.getAttribute("name");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글쓰기</title>
</head>
<body>
<h2>글쓰기</h2>
<form method="post" action="./write_ok.jsp" enctype="multipart/form-data">
<p>작성자: <%=name %>(<%=userid%>)</p>
<p>제목: <input type="text" name="b_title"></p>
<p>내용</p>
<p><textarea style="width: 300px; height: 200px; resize: none;" name="b_content"></textarea></p>
<p><input type="file" name="b_file"></p>
<p><button>등록</button>
<button type = "reset">재작성</button>
<button type = "button" onclick = "location.href='list.jsp'"> 리스트 </button>
</p>
</form>
</body>
</html>
write_ok.jsp
<%@page import="java.util.List"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.koreait.FileService" %>
<%@ page import="java.io.File" %>
<%
request.setCharacterEncoding("UTF-8");
FileService fs = new FileService();
String savePath = fs.SAVE_PATH;
int maxSize = fs.MAX_SIZE;
String format = fs.ENC_FORMAT;
String uploadFile = "";
File file;
try{
MultipartRequest mr = new MultipartRequest(request, savePath, maxSize,format, new DefaultFileRenamePolicy());
String userid = (String)session.getAttribute("userid");
String name = (String)session.getAttribute("name");
String b_title = mr.getParameter("b_title"); /* 라이브러리가 대신 받아줌 */
String b_content = mr.getParameter("b_content");
uploadFile = mr.getFilesystemName("b_file");
file = new File(savePath + "/" + uploadFile);
if(fs.dataUpload(userid, name, b_title, b_content, file)){
out.print("<script>alert('등록되었습니다');location.href='./list.jsp';</script>");
}else{
out.print("<script>alert('error');history.back()</script>");
}
}catch(Exception e){
e.printStackTrace();
}
%>
fileservice.java
package com.koreait;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.koreait.db.FileBoardDAO;
import com.koreait.db.FileBoardDTO;
public class FileService {
public static String SAVE_PATH = "/Users/jaewon/Desktop/onedrive/study/JSP/Day7/src/main/webapp/board/upload";
public static int MAX_SIZE = 1024 * 1024 * 100; //100mb
public static String ENC_FORMAT = "UTF-8";
private FileBoardDAO fileBoardDAO = null;
public FileService() {
fileBoardDAO = new FileBoardDAO();
}
public boolean dataUpload(String userid, String name, String title, String content, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
boolean isSuccess = fileBoardDAO.insertData(fileBoardDTO);
if(isSuccess){
moveFile(fileBoardDTO,file);
}
return isSuccess;
}
public boolean nodataEdit(String userid, String name, String title, String content,int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
System.out.println("fs 36 userid" + userid);
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setIdx(idx);
boolean isSuccess = fileBoardDAO.updateData(fileBoardDTO);
return isSuccess;
}
public boolean delfiledataEdit(String userid, String name, String title, String content,int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
System.out.println("fs 36 userid" + userid);
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setIdx(idx);
boolean isSuccess = fileBoardDAO.updateDatadelfile(fileBoardDTO);
return isSuccess;
}
public boolean dataEdit(String userid, String name, String title, String content, int idx, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
fileBoardDTO.setIdx(idx);
System.out.println("fs 51 line "+ fileBoardDTO.getFilename());
boolean isSuccess = fileBoardDAO.updatefileData(fileBoardDTO);
System.out.println("fs53");
if(isSuccess){
moveFile(fileBoardDTO,file);
System.out.println("fs55");
}
System.out.println("fs58");
return isSuccess;
}
public boolean datainsertEdit(String userid, String name, String title, String content, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
System.out.println("fs 80 line"+ fileBoardDTO.getFilename());
boolean isSuccess = fileBoardDAO.updateData(fileBoardDTO);
System.out.println("fs82");
if(isSuccess){
moveFile(fileBoardDTO,file);
System.out.println("fs85");
}
System.out.println("fs87");
return isSuccess;
}
public void moveFile(FileBoardDTO fileBoardDTO,File file) {
File dir = new File(SAVE_PATH + "/" + getToday());
if(!dir.isDirectory()) {
dir.mkdir();
}
if(file.isFile()) {
File newFile = new File(SAVE_PATH + fileBoardDTO.getFilepath());
file.renameTo(newFile);
}
}
public boolean delFile(int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setIdx(idx);
fileBoardDTO = fileBoardDAO.getData(fileBoardDTO);
String deleteImg =fileBoardDTO.getFilepath();
System.out.println("deleteImg : "+ deleteImg);
String deleteImgFullPath = SAVE_PATH + deleteImg;
System.out.println("deleteImgFullPath : " + deleteImgFullPath);
File img = new File(deleteImgFullPath);
if(img.exists() && img.isFile()){
System.out.println("fileservice 85line");
img.delete();
System.out.println("fileservice 87에러안남");
return true;
}
System.out.println("fileservice 90");
return false;
}
public static String getToday() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(cal.getTime());
}
}
fileboardDTO.java
package com.koreait.db;
public class FileBoardDTO {
private int idx;
private String userid;
private String name;
private String title;
private String content;
private int hit;
private int like;
private String regdate;
private String filename;
private String filepath;
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getHit() {
return hit;
}
public void setHit(int hit) {
this.hit = hit;
}
public int getLike() {
return like;
}
public void setLike(int like) {
this.like = like;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
}
fileboardDAO.java
package com.koreait.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.koreait.FileService;
public class FileBoardDAO {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
String[] generatedColumns = {"b_idx"};
public boolean insertData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "insert into tb_fileboard(b_userid,b_name,b_title,b_content,b_filename) values(?,?,?,?,?)";
pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, fileBoardDTO.getFilename());
int result = pstmt.executeUpdate();
try(ResultSet geneResultKey = pstmt.getGeneratedKeys()){
if(geneResultKey.next()) {
fileBoardDTO.setIdx(geneResultKey.getInt(1));
}
}
if(result >= 1) {
fileBoardDTO = this.updateFilePath(fileBoardDTO);
return true;
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public boolean updateData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setInt(5, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
System.out.println("fileboarddao_56 성공했따 십새키");
return true;
}
}catch(Exception e) {
System.out.println("fileboarddao_60 에러났다 십새키");
e.printStackTrace();
}
return false;
}
public boolean updateDatadelfile(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=?,b_filename=?,b_filepath=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, null);
pstmt.setString(6, null);
pstmt.setInt(7, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
System.out.println("fileboarddao_56 성공했따 십새키");
return true;
}
}catch(Exception e) {
System.out.println("fileboarddao_60 에러났다 십새키");
e.printStackTrace();
}
return false;
}
public boolean updatefileData(FileBoardDTO fileBoardDTO) {
try {
System.out.println("fildao실행");
System.out.println("fileBoardDTO.getUserid() = "+fileBoardDTO.getUserid());
System.out.println("fileBoardDTO.getName() = "+fileBoardDTO.getName());
System.out.println("fileBoardDTO.getTitle() = "+fileBoardDTO.getTitle());
System.out.println("fileBoardDTO.getContent() = "+fileBoardDTO.getContent());
System.out.println("fileBoardDTO.getFilename() = "+fileBoardDTO.getFilename());
System.out.println("fileBoardDTO.getIdx() = "+fileBoardDTO.getIdx());
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=?,b_filename=? where b_idx=?";
pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, fileBoardDTO.getFilename());
pstmt.setInt(6, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
fileBoardDTO = this.updateFilePath(fileBoardDTO);
return true;
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public FileBoardDTO getData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "select * from tb_fileboard where b_idx = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,fileBoardDTO.getIdx());
rs = pstmt.executeQuery();
while(rs.next()) {
fileBoardDTO.setFilepath(rs.getString("b_filepath"));
}
}catch(Exception e) {
e.printStackTrace();
}
return fileBoardDTO;
}
public FileBoardDTO updateFilePath(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_filepath=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
String tmp = "/" + FileService.getToday() + "/" + fileBoardDTO.getFilename();
fileBoardDTO.setFilepath(tmp);
pstmt.setString(1,tmp);
pstmt.setInt(2,fileBoardDTO.getIdx());
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return fileBoardDTO;
}
}
글수정하기(첨부파일수정하기)
edit.jsp
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@ page import="com.koreait.db.Dbconn"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%
String userid = (String)session.getAttribute("userid");
String name = (String)session.getAttribute("name");
String num = request.getParameter("b_idx");
request.setCharacterEncoding("UTF-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String b_title ="";
String b_content = "";
String b_filename = "";
String b_filepath = "";
try{
conn = Dbconn.getConnection();
if(conn != null){
/* System.out.println("DB연결 성공!"); */
String sql = "select * from tb_fileboard where b_idx = ?";
pstmt = conn.prepareStatement(sql); //컴파일하고 나서 set 설정해줘야함!
pstmt.setString(1, num );
rs = pstmt.executeQuery();
while(rs.next()){
b_title = rs.getString("b_title");
b_content = rs.getString("b_content");
b_filename = rs.getString("b_filename");
b_filepath = rs.getString("b_filepath");
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글수정</title>
<style>
.b_file{
display: none;
}
.b_file.visible{
display:block;
}
.chbtn.disable{
display: none;0
}
</style>
<body>
<h2>글수정</h2>
<form method="post" action="./edit_ok.jsp" enctype="multipart/form-data">
<input type="hidden" name="b_idx" value="<%=num%>">
<p>작성자: <%=name %>(<%=userid%>)</p>
<p>제목: <input type="text" name="b_title" value=<%=b_title%>></p>
<p>내용</p>
<p><textarea style="width: 300px; height: 200px; resize: none;" name="b_content" ><%=b_content%></textarea></p>
<%
if(b_filename==null){
%>
<p><input type="file" name="b_file"></p><input type="hidden" class ="para" name="para" value="new">
<%
}else{
%>
<p><input type="file" class="b_file" name="b_file"><span class="chbtn" ><%=b_filename%> <input type="hidden" class ="para" name="para" value=<%=b_filename %>> <button type="button" onclick="visible()">X</button></span></p>
<% }%>
<p><button>수정</button>
<button type = "reset">재작성</button>
<button type = "button" onclick = "history.back()"> 뒤로 </button>
</p>
</form>
<script>
const chbtn = document.querySelector('.chbtn');
const filetag = document.querySelector('.b_file');
const para = document.querySelector('.para');
function visible(){
para.removeAttribute('value');
chbtn.classList.add('disable');
filetag.classList.add('visible');
}
</script>
</body>
</html>
edit_ok.jsp
<%@page import="java.util.List"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="com.koreait.db.Dbconn"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/sessioncheck.jsp"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.koreait.FileService" %>
<%@ page import="java.io.File" %>
<%
request.setCharacterEncoding("UTF-8");
FileService fs = new FileService();
String savePath = fs.SAVE_PATH;
int maxSize = fs.MAX_SIZE;
String format = fs.ENC_FORMAT;
String uploadFile = "";
File file;
MultipartRequest mr = new MultipartRequest(request, savePath, maxSize,format, new DefaultFileRenamePolicy());
String para = mr.getParameter("para");
String userid = (String)session.getAttribute("userid");
String name = (String)session.getAttribute("name");
String b_title = (String)mr.getParameter("b_title");
String b_content = (String)mr.getParameter("b_content");
String b_file = mr.getFilesystemName("b_file"); //첨부한 파일의 이름을 문자열로받으려면 getFilesystemName사용해야함! getParameter하면 null반환
uploadFile = mr.getFilesystemName("b_file");
file = new File(savePath + "/" + uploadFile);
System.out.println("edit ok new b_file is "+ b_file); //새롭게 첨부해서 넘어온 파일
System.out.println("edit ok title is "+b_title);
int b_idx = Integer.parseInt(mr.getParameter("b_idx"));
if(para.equals("")){
System.out.println("edit ok b_idx is "+ b_idx);
if(b_file!=null){
System.out.println("edit ok 첨부파일 변경하려고 x하고 새롭게 첨부한경우");
try{
file = new File(savePath + "/" + uploadFile);
if(fs.delFile(b_idx)){
System.out.println("edit ok 실제 기존에 있던파일은 삭제 성공");
if(fs.dataEdit(userid, name, b_title, b_content, b_idx, file)){
out.print("<script>alert('수정되었습니다');location.href='./list.jsp';</script>");
}else{
out.print("<script>alert('2error');history.back()</script>");
}
}
}catch(Exception e){
System.out.println("edit_ok_54line");
e.printStackTrace();
}
}else{
System.out.println("첨부파일 변경하려고 x했지만 첨부를 안해버린경우 삭제에 해당");
try{
file = new File(savePath + "/" + uploadFile);
if(fs.delFile(b_idx)){
if(fs.delfiledataEdit(userid, name, b_title, b_content, b_idx)){
out.print("<script>alert('수정되었습니다');location.href='./list.jsp';</script>");
}else{
out.print("<script>alert('3error');history.back()</script>");
}
}
}catch(Exception e){
System.out.println("edit_ok_74");
e.printStackTrace();
}
}
}else if(para.equals("new")){
System.out.println("첨부파일없던 글에 첨부파일 첨부한것");
try{
file = new File(savePath + "/" + uploadFile);
if(fs.dataEdit(userid, name, b_title, b_content, b_idx, file)){
out.print("<script>alert('수정되었습니다');location.href='./list.jsp';</script>");
}else{
out.print("<script>alert('2error');history.back()</script>");
}
}catch(Exception e){
System.out.println("edit_ok_54line");
e.printStackTrace();
}
}
else {
System.out.println("첨부파일 그대로 두고 글,제목만 수정");
if(fs.nodataEdit(userid, name, b_title, b_content,b_idx)){
out.print("<script>alert('수정되었습니다');location.href='./list.jsp';</script>");
}else{
out.print("<script>alert('1error');history.back()</script>");
}
}
%>
fileservice.java,filaboardDAO,fileboardDTO (중복 이라서 접은글로함)
더보기
fileservice.java
package com.koreait;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.koreait.db.FileBoardDAO;
import com.koreait.db.FileBoardDTO;
public class FileService {
public static String SAVE_PATH = "/Users/jaewon/Desktop/onedrive/study/JSP/Day7/src/main/webapp/board/upload";
public static int MAX_SIZE = 1024 * 1024 * 100; //100mb
public static String ENC_FORMAT = "UTF-8";
private FileBoardDAO fileBoardDAO = null;
public FileService() {
fileBoardDAO = new FileBoardDAO();
}
public boolean dataUpload(String userid, String name, String title, String content, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
boolean isSuccess = fileBoardDAO.insertData(fileBoardDTO);
if(isSuccess){
moveFile(fileBoardDTO,file);
}
return isSuccess;
}
public boolean nodataEdit(String userid, String name, String title, String content,int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
System.out.println("fs 36 userid" + userid);
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setIdx(idx);
boolean isSuccess = fileBoardDAO.updateData(fileBoardDTO);
return isSuccess;
}
public boolean delfiledataEdit(String userid, String name, String title, String content,int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
System.out.println("fs 36 userid" + userid);
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setIdx(idx);
boolean isSuccess = fileBoardDAO.updateDatadelfile(fileBoardDTO);
return isSuccess;
}
public boolean dataEdit(String userid, String name, String title, String content, int idx, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
fileBoardDTO.setIdx(idx);
System.out.println("fs 51 line "+ fileBoardDTO.getFilename());
boolean isSuccess = fileBoardDAO.updatefileData(fileBoardDTO);
System.out.println("fs53");
if(isSuccess){
moveFile(fileBoardDTO,file);
System.out.println("fs55");
}
System.out.println("fs58");
return isSuccess;
}
public boolean datainsertEdit(String userid, String name, String title, String content, File file) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setUserid(userid);
fileBoardDTO.setName(name);
fileBoardDTO.setTitle(title);
fileBoardDTO.setContent(content);
fileBoardDTO.setFilename(file.getName());
System.out.println("fs 80 line"+ fileBoardDTO.getFilename());
boolean isSuccess = fileBoardDAO.updateData(fileBoardDTO);
System.out.println("fs82");
if(isSuccess){
moveFile(fileBoardDTO,file);
System.out.println("fs85");
}
System.out.println("fs87");
return isSuccess;
}
public void moveFile(FileBoardDTO fileBoardDTO,File file) {
File dir = new File(SAVE_PATH + "/" + getToday());
if(!dir.isDirectory()) {
dir.mkdir();
}
if(file.isFile()) {
File newFile = new File(SAVE_PATH + fileBoardDTO.getFilepath());
file.renameTo(newFile);
}
}
public boolean delFile(int idx) {
FileBoardDTO fileBoardDTO = new FileBoardDTO();
fileBoardDTO.setIdx(idx);
fileBoardDTO = fileBoardDAO.getData(fileBoardDTO);
String deleteImg =fileBoardDTO.getFilepath();
System.out.println("deleteImg : "+ deleteImg);
String deleteImgFullPath = SAVE_PATH + deleteImg;
System.out.println("deleteImgFullPath : " + deleteImgFullPath);
File img = new File(deleteImgFullPath);
if(img.exists() && img.isFile()){
System.out.println("fileservice 85line");
img.delete();
System.out.println("fileservice 87에러안남");
return true;
}
System.out.println("fileservice 90");
return false;
}
public static String getToday() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(cal.getTime());
}
}
fileboardDAO.java
package com.koreait.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.koreait.FileService;
public class FileBoardDAO {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
String[] generatedColumns = {"b_idx"};
public boolean insertData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "insert into tb_fileboard(b_userid,b_name,b_title,b_content,b_filename) values(?,?,?,?,?)";
pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, fileBoardDTO.getFilename());
int result = pstmt.executeUpdate();
try(ResultSet geneResultKey = pstmt.getGeneratedKeys()){
if(geneResultKey.next()) {
fileBoardDTO.setIdx(geneResultKey.getInt(1));
}
}
if(result >= 1) {
fileBoardDTO = this.updateFilePath(fileBoardDTO);
return true;
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public boolean updateData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setInt(5, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
System.out.println("fileboarddao_56 성공했따 십새키");
return true;
}
}catch(Exception e) {
System.out.println("fileboarddao_60 에러났다 십새키");
e.printStackTrace();
}
return false;
}
public boolean updateDatadelfile(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=?,b_filename=?,b_filepath=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, null);
pstmt.setString(6, null);
pstmt.setInt(7, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
System.out.println("fileboarddao_56 성공했따 십새키");
return true;
}
}catch(Exception e) {
System.out.println("fileboarddao_60 에러났다 십새키");
e.printStackTrace();
}
return false;
}
public boolean updatefileData(FileBoardDTO fileBoardDTO) {
try {
System.out.println("fildao실행");
System.out.println("fileBoardDTO.getUserid() = "+fileBoardDTO.getUserid());
System.out.println("fileBoardDTO.getName() = "+fileBoardDTO.getName());
System.out.println("fileBoardDTO.getTitle() = "+fileBoardDTO.getTitle());
System.out.println("fileBoardDTO.getContent() = "+fileBoardDTO.getContent());
System.out.println("fileBoardDTO.getFilename() = "+fileBoardDTO.getFilename());
System.out.println("fileBoardDTO.getIdx() = "+fileBoardDTO.getIdx());
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_userid=?,b_name=?,b_title=?,b_content=?,b_filename=? where b_idx=?";
pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, fileBoardDTO.getUserid());
pstmt.setString(2, fileBoardDTO.getName());
pstmt.setString(3, fileBoardDTO.getTitle());
pstmt.setString(4, fileBoardDTO.getContent());
pstmt.setString(5, fileBoardDTO.getFilename());
pstmt.setInt(6, fileBoardDTO.getIdx());
int result = pstmt.executeUpdate();
if(result >= 1) {
fileBoardDTO = this.updateFilePath(fileBoardDTO);
return true;
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public FileBoardDTO getData(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "select * from tb_fileboard where b_idx = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,fileBoardDTO.getIdx());
rs = pstmt.executeQuery();
while(rs.next()) {
fileBoardDTO.setFilepath(rs.getString("b_filepath"));
}
}catch(Exception e) {
e.printStackTrace();
}
return fileBoardDTO;
}
public FileBoardDTO updateFilePath(FileBoardDTO fileBoardDTO) {
try {
conn = Dbconn.getConnection();
sql = "update tb_fileboard set b_filepath=? where b_idx=?";
pstmt = conn.prepareStatement(sql);
String tmp = "/" + FileService.getToday() + "/" + fileBoardDTO.getFilename();
fileBoardDTO.setFilepath(tmp);
pstmt.setString(1,tmp);
pstmt.setInt(2,fileBoardDTO.getIdx());
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return fileBoardDTO;
}
}
fileboardDTO.java
package com.koreait.db;
public class FileBoardDTO {
private int idx;
private String userid;
private String name;
private String title;
private String content;
private int hit;
private int like;
private String regdate;
private String filename;
private String filepath;
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getHit() {
return hit;
}
public void setHit(int hit) {
this.hit = hit;
}
public int getLike() {
return like;
}
public void setLike(int like) {
this.like = like;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
}
반응형
'웹 개발 > 🎆 JSP' 카테고리의 다른 글
three.js JSP에 적용하기 (0) | 2024.03.08 |
---|---|
JSP | postman,REST,JSON, Java CRAWLING (0) | 2022.12.05 |
JSP | JSP영역,EL표현식,JSTL,Maven,fileupload (0) | 2022.11.30 |
JSP | JavaBean,DAO,DTO (0) | 2022.11.29 |
JSP | JSP를이용한 홈페이지구현 - 게시판 (0) | 2022.11.27 |