관리 메뉴

거니의 velog

231006_AJAX 강의 본문

대덕인재개발원/대덕인재개발원_Front End

231006_AJAX 강의

Unlimited00 2023. 10. 6. 08:46

[부트스트랩 모달창 적용하기]
[join.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        <style>
        	input[type=button] {
        		margin: 5px;
        		border-radius: 30px;
        	}
        </style>
        <script>
        
	        const proc1 = () => {
	        	
				var dongVal = $("#dong").val().trim();
				console.log(dongVal);
				
				if(dongVal.length < 1) {
					alert("동이름을 입력하세요.");
					return false;
				}
				
				var dongReg = /^[가-힣]+$/;
				
				if(!(dongReg.test(dongVal))) {
					alert("형식 오류입니다.");
					return false;
				}
				
				$.ajax({
					url : 'http://localhost/memberpro/selectByDong.do',
					data : { "dong" : dongVal },
					type : 'post',
					success : function(res){
						var code = "<table class='table table-dark table-hover'>";
						code += "<tr><th>우편번호</th><th>주소</th><th>번지</th></tr>";
						$.each(res, function(i, v){
							var bunji = v.bunji;
							if(!bunji) { // if(typeof bunji == "undefined")
								bunji = "";
							}
							code += "<tr class='ziptr'><td>"+ v.zipcode +"</td>";
							code += "<td>"+ v.sido +" "+ v.gugun +" "+ v.dong +"</td>";
							code += "<td>"+ bunji +"</td></tr>";
						});
						code += "</table>";
						
						$("#result1").html(code);
					},
					error : function(xhr){
						alert("상태 : " + xhr.status);
					},
					dataType : 'json'
				});
				
			} // proc1 끝
            
            $(function(){
            	
            	$(document).on("click", ".ziptr", function(){
					var thisIs = $(this);
					var zipCode = thisIs.find("td").eq(0).text().trim();
					//console.log(zipCode);
					var address = thisIs.find("td").eq(1).text().trim();
					//console.log(address);
					$('#zip').val(zipCode);
					$('#add1').val(address);
					
					$('#dong').val("");
					$('#result1').empty();
					
					$('#myModal').modal('hide');
				});
                
                $("#idChkBtn").on("click", function(){
                	// 입력한 값 가져오기
                	var idVal = $("#id").val().trim();
                	//console.log(idVal);
                	// 값의 형식 비교
                	var idreg = /^[a-z][a-zA-Z0-9]{3,7}$/;
                	if(!(idreg.test(idVal))) {
                		alert("id 형식 오류입니다...");
                		return false;
                	}
                	// 서버로 전송
                	$.ajax({
                		url : "<%= request.getContextPath() %>/idCheck.do",
                		data : { "id" : idVal },
                		type : "get",
                		success : function(res){
                			//console.log(res);
                			$("#idChkTxt").html(res.flag).css("color", "red");
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                	
                });
                
                // 우편번호 검색
                $("#zipBtn").on("click", function(){
                	window.open("searchDong.html", "우편번호찾기", "width=500 height=400");
                });
                
                // 저장하기 - button type=submit인 경우
                // method와 action이 있는 경우 - button / submit
                // method와 action이 없는 경우 - button / submit
                /* $("#joinSubmitForm").on("submit", function(e){
                	// submit의 원래 고유 기능에 대한 이벤트를 제거한다.
                	e.preventDefault();
                	//alert("submit");
                }); */
                
             	// 저장하기 - button type=button인 경우
                $("#joinSubmitBtn").on("click", function(){
                	//alert("subBtn");
                	
                	/* // 입력한 모든 값을 가져온다.
                	// 공백, 형식 체크 - return false;
                	var idVal = $("#id").val().trim();
                	var nameVal = $("#name").val().trim();
                	var birthVal = $("#birth").val().trim();
                	var passVal = $("#pass").val().trim();
                	var hpVal = $("#hp").val().trim();
                	var emailVal = $("#email").val().trim();
                	var zipVal = $("#zip").val().trim();
                	var add1Val = $("#add1").val().trim();
                	var add2Val = $("#add2").val().trim();
                	
                	var data = { 
                		"id" : idVal,
                		"name" : nameVal,
                		"birth" : birthVal,
                		"pass" : passVal,
                		"hp" : hpVal,
                		"email" : emailVal,
                		"zip" : zipVal,
                		"add1" : add1Val,
                		"add2" : add2Val
                	}; */
                	
                	//console.log(data);
                	
                	var data = $("#joinSubmitForm").serializeArray();
                	console.log(data);
                	
                	$.ajax({
                		url : "<%= request.getContextPath() %>/insertMember.do",
                		data : data,
                		type : "post",
                		success : function(res){
                			if(res.flag == "ok"){
                				alert(res.msg);
                				location.href = "<%= request.getContextPath() %>/memberListView.do"; // 서블릿으로 가야 함.
                			}else{
                				alert(res.msg);
                			}
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
            });
            
        </script>
	</head>
	<body>
	<!-- 
		-- public String idDuplChk(String id)
		select mem_id from member where mem_id = 'a001';
		
		-- public List<ZipVO> selectByDong(String dong)
		select * from ziptb where dong like '탄방%';
		
		-- public int insertMember(MemberVO memVo);
		INSERT INTO member (
		    mem_id,
		    mem_pass,
		    mem_name,
		    mem_bir,
		    mem_zip,
		    mem_add1,
		    mem_add2,
		    mem_hp,
		    mem_mail
		) VALUES (
		    'xyz001',
		    '1234567',
		    '고릴라',
		    '1999-08-12',
		    '135-932',
		    '대전 서구 둔산동',
		    '222-2번지 대전경찰서 1층 원무과',
		    '010-1234-5678',
		    'kkk1234@ddit.or.kr'
		);
		
		commit;
	 -->
	<div class="container mt-3">
		<h2>회원가입</h2>
		<form id="joinSubmitForm">
			<div class="mb-3 mt-3 col-sm-4">
				<label for="id">아이디</label> 
				<input id="idChkBtn" type="button" class="btn btn-outline-success btn-sm" value="중복검사" />
				<span id="idChkTxt"></span>
				<input type="text" class="form-control" id="id" name="mem_id">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">이름</label> 
				<input type="text" class="form-control" id="name" name="mem_name">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">생년월일</label> 
				<input type="date" class="form-control" id="birth" name="mem_bir">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="pass">비밀번호</label> 
				<input type="password" class="form-control" id="pass" name="mem_pass">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="hp">전화번호</label> 
				<input type="text" class="form-control" id="hp" name="mem_hp">
			</div>
			<div class="mb-3 col-sm-4">
		        <label for="email">이메일</label>
		        <input type="email" class="form-control" id="email" name="mem_mail">
		    </div>
		    <div class="mb-3 col-sm-4">
				<label for="zip">우편번호</label> 
				<input id="zipBtn" type="button" class="btn btn-outline-info btn-sm" value="번호검색" />
				<!-- 우편번호 Modal 버튼 -->
				<input data-bs-toggle="modal" data-bs-target="#myModal" type="button" class="btn btn-outline-info btn-sm" value="번호검색모달" />
				<input type="text" class="form-control" id="zip" name="mem_zip">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add1">주소</label> 
				<input type="text" class="form-control" id="add1" name="mem_add1">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add2">상세주소</label> 
				<input type="text" class="form-control" id="add2" name="mem_add2">
			</div>
			<!-- <button id="joinSubmit" type="submit" class="btn btn-primary btn-lg">제출</button> -->
			<button id="joinSubmitBtn" type="button" class="btn btn-primary btn-lg">submit</button>
			<button type="reset" class="btn btn-secondary btn-lg">초기화</button>
		</form>
	</div>
	
	<!-- 우편번호 Modal -->
	<div class="modal fade" id="myModal">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
	
	      <!-- Modal Header -->
	      <div class="modal-header">
	        <h4 class="modal-title">우편번호 찾기</h4>
	        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
	      </div>
	
	      <!-- Modal body -->
	      <div class="modal-body">
	        <p>찾는 동이름을 입력하세요</p>
			<input class="form-control" id="dong" type="text" />
			<input id="btn1" class="btn btn-primary" type="button" value="확인" onclick="proc1()" />
			
			<div id="result1"></div>
	      </div>
	
	      <!-- Modal footer -->
	      <div class="modal-footer">
	        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
	      </div>
	
	    </div>
	  </div>
	</div>
	
</body>
</html>

-------------------------------------------

select distinct sido from ziptb;

select distinct gugun from ziptb where sido = '대전';

select distinct dong from ziptb where sido = '대전' and gugun = '대덕구';

select * from ziptb where sido = '대전' and gugun = '대덕구' and dong = '법1동';

var serialVal = $("#joinSubmitForm").serialize()
console.log(serialVal);
var data = $("#joinSubmitForm").serializeArray();
console.log(data);

[Accordian 게시판]

---------------------------------------------------------------

select mem_id, mem_pass, mem_name from member 
		where mem_id = 'a001' and mem_pass = 'asdfasdf';
        
create table boardtab (
num			number	             not null	primary key,
subject			varchar2(50)	not null,
writer			varchar2(15)	not null,
mail			varchar2(30),
password		             varchar2(10)	not null,
content			varchar2(2000),
hit			number		not null,
wip			char(15)		not null,
wdate			date		not null
);

create table replytab(
renum  number              not null primary key,
bonum  number              not null,
name   varchar2(15)        not null,
cont   varchar2(1000)      not null,
redate   date			  not null,
CONSTRAINT REPLY_BONUM FOREIGN KEY(BONUM)
REFERENCES BOARDTAB(NUM)
ON DELETE CASCADE 
);

commit;

create sequence boardtab_num_seq nocache;
create sequence replytab_renum_seq nocache;

insert into boardtab values (boardtab_num_seq.nextval, '제목1', '이름1', 'test1@test.com', '1234', '내용1', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목2', '이름2', 'test2@test.com', '1234', '내용2', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목3', '이름3', 'test3@test.com', '1234', '내용3', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목4', '이름4', 'test4@test.com', '1234', '내용4', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목5', '이름5', 'test5@test.com', '1234', '내용5', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목6', '이름6', 'test6@test.com', '1234', '내용6', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목7', '이름7', 'test7@test.com', '1234', '내용7', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목8', '이름8', 'test8@test.com', '1234', '내용8', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목9', '이름9', 'test9@test.com', '1234', '내용9', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목10', '이름10', 'test10@test.com', '1234', '내용10', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목11', '이름11', 'test11@test.com', '1234', '내용11', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목12', '이름12', 'test12@test.com', '1234', '내용12', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목13', '이름13', 'test13@test.com', '1234', '내용13', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목14', '이름14', 'test14@test.com', '1234', '내용14', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목15', '이름15', 'test15@test.com', '1234', '내용15', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목16', '이름16', 'test16@test.com', '1234', '내용16', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목17', '이름17', 'test17@test.com', '1234', '내용17', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목18', '이름18', 'test18@test.com', '1234', '내용18', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목19', '이름19', 'test19@test.com', '1234', '내용19', 0, '000.000.000.000', sysdate);
insert into boardtab values (boardtab_num_seq.nextval, '제목20', '이름20', 'test20@test.com', '1234', '내용20', 0, '000.000.000.000', sysdate);

commit;

select count(*) from boardtab;

select 'private ' || 
        decode(lower(data_type), 'number', 'int ', 'String ') || 
        lower(column_name) || ';'
  from cols
 where lower(table_name) = 'boardtab';

[mybatis-config.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration 
	PUBLIC "-//mybatis.org/DTD Config 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="kr/or/ddit/mybatis/config/dbinfo.properties" />
	
	<settings>
		<setting name="jdbcTypeForNull" value="NULL" />
	</settings>
	
	<typeAliases>
		<typeAlias type="kr.or.ddit.member.vo.MemberVO" alias="memberVo" />
		<typeAlias type="kr.or.ddit.member.vo.ZipVO" alias="zipVo" />
		<typeAlias type="kr.or.ddit.board.vo.BoardVO" alias="boardVo" />
		<typeAlias type="kr.or.ddit.reply.vo.ReplyVO" alias="replyVo" />
	</typeAliases>
	
	<!-- DB연결 설정 -->
	<environments default="oracleDev">
		<environment id="oracleDev">
			<!-- 오라클 -->
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${user}" />
				<property name="password" value="${pass}" />
			</dataSource>
		</environment>
		<!-- <environment id="m1">
			MySql
		</environment> -->
	</environments>
	
	<mappers>
		<mapper resource="kr/or/ddit/mybatis/mapper/member.xml" />
		<mapper resource="kr/or/ddit/mybatis/mapper/board.xml" />
		<mapper resource="kr/or/ddit/mybatis/mapper/reply.xml" />
	</mappers>
</configuration>

[member.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper 
	PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="member">
	
	<select id="searchByIdPass" parameterType="map" resultType="memberVo">
		select * from member where mem_id = #{id} and mem_pass = #{pass}
	</select>
	
</mapper>

[IMemberDAO.java]

package kr.or.ddit.member.dao;

import java.util.Map;

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

public interface IMemberDAO {
	
	// id, pass 검색 데이터 가져오기
	public MemberVO searchByIdPass(Map<String, Object> map);
	
}

[MemberDaoImpl.java]

package kr.or.ddit.member.dao;

import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import kr.or.ddit.member.vo.MemberVO;
import kr.or.ddit.mybatis.config.MyBatisUtil;

/*
 * Data Access Object
 * SqlSession객체가 필요.
 * Singleton을 통해 자신의 객체를 생성해서 return하는 메소드 필요(getDaoInstance()).
 */
public class MemberDaoImpl implements IMemberDAO {

	// 싱글톤 패턴
	private static MemberDaoImpl dao;
	private MemberDaoImpl() {}
	public static MemberDaoImpl getInstance() {
		if(dao == null) dao = new MemberDaoImpl();
		return dao;
	}

	@Override
	public MemberVO searchByIdPass(Map<String, Object> map) {
		SqlSession session = null;
		MemberVO memVo = null;
		
		try {
			session = MyBatisUtil.getSqlSession();
			memVo = session.selectOne("member.searchByIdPass", map);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return memVo;
	}

}

[IMemberService.java]

package kr.or.ddit.member.service;

import java.util.Map;

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

public interface IMemberService {
	
	// id, pass 검색 데이터 가져오기
	public MemberVO searchByIdPass(Map<String, Object> map);
	
}

[MemberServiceImpl.java]

package kr.or.ddit.member.service;

import java.util.Map;

import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.member.vo.MemberVO;

/*
 * DAO 객체가 필요
 * 싱글톤을 위한 자기 자신의 객체를 생성해서 리턴하는 메소드
 */
public class MemberServiceImpl implements IMemberService {

	private IMemberDAO dao;
	
	// 싱글톤 패턴
	private static MemberServiceImpl service;
	private MemberServiceImpl() {
		dao = MemberDaoImpl.getInstance();
	}
	public static MemberServiceImpl getInstance() {
		if(service == null) service = new MemberServiceImpl();
		return service;
	}

	@Override
	public MemberVO searchByIdPass(Map<String, Object> map) {
		return dao.searchByIdPass(map);
	}

}

[board.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper 
	PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="board">
	
	<sql id="dynamicCondition">
		<where>
			<if test="!(stype == '' or sword == '')">
				${stype} like '%' || #{sword} || '%'
			</if>
		</where>
	</sql>
	
	<!-- 게시판 글 리스트 조건에 따라  3개씩 출력 -->
	<select id="selectBoardList" parameterType="map" resultType="boardVo">
		select A.*
		  from (
		        select rownum as rnum
		             , B.*  
		          from (select * from boardtab 
		          		 <include refid="dynamicCondition" /> 
		          		 order by num desc) B
		 <![CDATA[
		         where rownum <= #{end}
		        ) A
		 where A.rnum >= #{start}
		 ]]>
	</select>
	
	<!-- 게시판 글 갯수 - 조건에 따라 수행 -->
	<select id="getTotalCnt" parameterType="map" resultType="int">
		select count(*) 
		  from boardtab 
		 <include refid="dynamicCondition" /> 
	</select>
	
	<!-- 삭제 결과 : int, param : 글번호(int), id이름 = 메소드 이름 -->
	<delete id="deleteBoard" parameterType="int">
		delete from boardtab where num = #{num}
	</delete>
	
	<!-- 수정 결과 : int, param : vo, id이름 = 메소드 이름 -->
	<update id="updateBoard" parameterType="boardVo">
		update boardtab set subject = #{subject}, mail = #{mail}, content = #{content}, wip = #{wip}, wdate = sysdate
		 where num = #{num}
	</update>
	
	<!-- 조회수 증가 결과 : int, param : 글번호(int), id이름 = 메소드 이름 -->
	<update id="updateHit" parameterType="int">
		update boardtab set hit = hit + 1 
		 where num = #{num}
	</update>
	
	<!-- 저장하기 결과 : int, param : vo, id이름 = 메소드 이름 -->
	<insert id="insertBoard" parameterType="boardVo">
		insert into boardtab (num, subject, writer, mail, password, content, hit, wip, wdate) 
		values (boardtab_num_seq.nextval, #{subject}, #{writer}, #{mail}, #{password}, #{content}, 0, #{wip}, sysdate)
	</insert>
	
</mapper>

[IBoardDAO.java]

package kr.or.ddit.board.dao;

import java.util.List;
import java.util.Map;

import kr.or.ddit.board.vo.BoardVO;

public interface IBoardDAO {

	// 리스트 가져오기 - 한 페이지당 3(n)개씩
	public List<BoardVO> selectBoardList(Map<String, Object> map);
	
	// 전체 글 갯수 구하기
	public int getTotalCnt(Map<String, Object> map);
	
	// 저장
	public int insertBoard(BoardVO vo);
	
	// 수정
	public int updateBoard(BoardVO vo);
	
	// 삭제
	public int deleteBoard(int bno);
	
	// 조회수 증가
	public int updateHit(int bno);
	
}

[BoardDaoImpl.java]

package kr.or.ddit.board.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import kr.or.ddit.board.vo.BoardVO;
import kr.or.ddit.mybatis.config.MyBatisUtil;

public class BoardDaoImpl implements IBoardDAO {

	private static BoardDaoImpl dao;
	private BoardDaoImpl() {}
	public static BoardDaoImpl getInstance() {
		if(dao == null) dao = new BoardDaoImpl();
		return dao;
	}
	
	@Override
	public List<BoardVO> selectBoardList(Map<String, Object> map) {
		SqlSession session = MyBatisUtil.getSqlSession();
		List<BoardVO> boardList = null;
		
		try {
			boardList = session.selectList("board.selectBoardList", map);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return boardList;
	}

	@Override
	public int getTotalCnt(Map<String, Object> map) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.selectOne("board.getTotalCnt", map);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int insertBoard(BoardVO vo) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.insert("board.insertBoard", vo);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int updateBoard(BoardVO vo) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.update("board.updateBoard", vo);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int deleteBoard(int bno) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.delete("board.deleteBoard", bno);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int updateHit(int bno) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.update("board.updateHit", bno);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

}

[IBoardService.java]

package kr.or.ddit.board.service;

import java.util.List;
import java.util.Map;

import kr.or.ddit.board.vo.BoardVO;

public interface IBoardService {

	// 리스트 가져오기 - 한 페이지당 3(n)개씩
	public List<BoardVO> selectBoardList(Map<String, Object> map);
	
	// 전체 글 갯수 구하기
	public int getTotalCnt(Map<String, Object> map);
	
	// 저장
	public int insertBoard(BoardVO vo);
	
	// 수정
	public int updateBoard(BoardVO vo);
	
	// 삭제
	public int deleteBoard(int bno);
	
	// 조회수 증가
	public int updateHit(int bno);
	
}

[BoardServiceImpl.java]

package kr.or.ddit.board.service;

import java.util.List;
import java.util.Map;

import kr.or.ddit.board.dao.BoardDaoImpl;
import kr.or.ddit.board.dao.IBoardDAO;
import kr.or.ddit.board.vo.BoardVO;

public class BoardServiceImpl implements IBoardService {

	private IBoardDAO dao;
	
	// 싱글톤 패턴
	private static BoardServiceImpl service;
	private BoardServiceImpl() {
		dao = BoardDaoImpl.getInstance();
	}
	public static BoardServiceImpl getInstance() {
		if(service == null) service = new BoardServiceImpl();
		return service;
	}
	
	@Override
	public List<BoardVO> selectBoardList(Map<String, Object> map) {
		return dao.selectBoardList(map);
	}

	@Override
	public int getTotalCnt(Map<String, Object> map) {
		return dao.getTotalCnt(map);
	}

	@Override
	public int insertBoard(BoardVO vo) {
		return dao.insertBoard(vo);
	}

	@Override
	public int updateBoard(BoardVO vo) {
		return dao.updateBoard(vo);
	}

	@Override
	public int deleteBoard(int bno) {
		return dao.deleteBoard(bno);
	}

	@Override
	public int updateHit(int bno) {
		return dao.updateHit(bno);
	}

}

[reply.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper 
	PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="reply">
	
	<!-- 댓글 삭제 결과 : int, param : 댓글번호(int), id이름 = 메소드 이름 -->
	<delete id="deleteReply" parameterType="int">
		DELETE FROM replytab
		WHERE renum = #{renum}
	</delete>
	
	<!-- 댓글 수정 결과 : int, param : vo, id이름 = 메소드 이름 -->
	<update id="updateReply" parameterType="replyVo">
		UPDATE replytab SET cont = #{cont}, redate = sysdate
		WHERE renum = #{renum} AND bonum = #{bonum}
	</update>
	
	<!-- 댓글 저장 결과 : int, param : vo, id이름 = 메소드 이름 -->
	<insert id="insertReply" parameterType="replyVo">
		INSERT INTO replytab (renum, bonum, name, cont, redate) 
		VALUES (replytab_renum_seq.nextval, #{bonum}, #{name}, #{cont}, sysdate)
	</insert>
	
	<!-- 댓글 리스트 결과 : vo, param : 게시판번호(int), id이름 = 메소드 이름 -->
	<select id="listReply" parameterType="int" resultType="replyVo">
		select * from replytab 
		where bonum = #{bonum}
	</select>
	
</mapper>

[IReplyDAO.java]

package kr.or.ddit.reply.dao;

import java.util.List;

import kr.or.ddit.reply.vo.ReplyVO;

public interface IReplyDAO {

	// 댓글 저장 - 리턴 : int, param : ReplyVO, 메소드이름 : insertReply
	public int insertReply(ReplyVO vo);
	
	// 댓글 삭제 - 리턴 : int, param : int, 메소드이름 : deleteReply
	public int deleteReply(int rno);
	
	// 댓글 수정 - 리턴 : int, param : ReplyVO, 메소드이름 : updateReply
	public int updateReply(ReplyVO vo);
	
	// 댓글 리스트 - 리턴 : List, param : int, 메소드이름 : listReply
	public List<ReplyVO> listReply(int bno);
	
}

[ReplyDaoImpl.java]

package kr.or.ddit.reply.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import kr.or.ddit.mybatis.config.MyBatisUtil;
import kr.or.ddit.reply.vo.ReplyVO;

public class ReplyDaoImpl implements IReplyDAO {

	private static ReplyDaoImpl dao;
	private ReplyDaoImpl() {}
	public static ReplyDaoImpl getInstance() {
		if(dao == null) dao = new ReplyDaoImpl();
		return dao;
	}
	
	@Override
	public int insertReply(ReplyVO vo) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.insert("reply.insertReply", vo);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int deleteReply(int rno) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.delete("reply.deleteReply", rno);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public int updateReply(ReplyVO vo) {
		SqlSession session = MyBatisUtil.getSqlSession();
		int cnt = 0;
		
		try {
			cnt = session.update("reply.updateReply", vo);
			if(cnt > 0) session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return cnt;
	}

	@Override
	public List<ReplyVO> listReply(int bno) {
		SqlSession session = MyBatisUtil.getSqlSession();
		List<ReplyVO> replyList = null;
		
		try {
			replyList = session.selectList("reply.listReply", bno);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}

		return replyList;
	}

}

[IReplyService.java]

package kr.or.ddit.reply.controller;

import java.util.List;

import kr.or.ddit.reply.vo.ReplyVO;

public interface IReplyService {

	// 댓글 저장 - 리턴 : int, param : ReplyVO, 메소드이름 : insertReply
	public int insertReply(ReplyVO vo);
	
	// 댓글 삭제 - 리턴 : int, param : int, 메소드이름 : deleteReply
	public int deleteReply(int rno);
	
	// 댓글 수정 - 리턴 : int, param : ReplyVO, 메소드이름 : updateReply
	public int updateReply(ReplyVO vo);
	
	// 댓글 리스트 - 리턴 : List, param : int, 메소드이름 : listReply
	public List<ReplyVO> listReply(int bno);
	
}

[ReplyServiceImpl.java]

package kr.or.ddit.reply.controller;

import java.util.List;

import kr.or.ddit.reply.dao.IReplyDAO;
import kr.or.ddit.reply.dao.ReplyDaoImpl;
import kr.or.ddit.reply.vo.ReplyVO;

public class ReplyServiceImpl implements IReplyService {

	private IReplyDAO dao;
	
	private static ReplyServiceImpl service;
	private ReplyServiceImpl() {
		dao = ReplyDaoImpl.getInstance();
	}
	public static ReplyServiceImpl getInstance() {
		if(service == null) service = new ReplyServiceImpl();
		return service;
	}
	
	@Override
	public int insertReply(ReplyVO vo) {
		return dao.insertReply(vo);
	}

	@Override
	public int deleteReply(int rno) {
		return dao.deleteReply(rno);
	}

	@Override
	public int updateReply(ReplyVO vo) {
		return dao.updateReply(vo);
	}

	@Override
	public List<ReplyVO> listReply(int bno) {
		return dao.listReply(bno);
	}

}

[temp.html]

<!DOCTYPE html>
<html lang="ko">
	<head>
		<title>Bootstrap Example</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
		<style>
			.card-body {
				display: flex;
				flex-direction: column;
			}
			.divCont {
				display: flex;
				flex-direction: row;
			}
			.divCont1 {
				flex: 70%;
			}
			.divCont2 {
				flex: 30%;
			}
		</style>
	</head>
	<body>
	
		<div class="container mt-3">
			<h2>Accordion Example</h2>
			<div id="accordion">
				<div class="card">
					<div class="card-header">
						<a class="btn" data-bs-toggle="collapse" href="#collapseOne">
							게시판 글제목
						</a>
					</div>
					<div id="collapseOne" class="collapse show" data-bs-parent="#accordion">
						<div class="card-body">
							<div class="divCont">
								<div class="divCont1">작성자 이메일 조회수 날짜</div>
								<div class="divCont2">수정삭제버튼</div>
							</div>
							<div>내용</div>
							<div>댓글쓰기 textarea 등록버튼</div>
						</div>
					</div>
				</div>
				<div class="card">
					<div class="card-header">
						<a class="collapsed btn" data-bs-toggle="collapse" href="#collapseTwo"> 
							게시판 글제목
						</a>
					</div>
					<div id="collapseTwo" class="collapse" data-bs-parent="#accordion">
						<div class="card-body">
							<div class="divCont">
								<div class="divCont1">작성자 이메일 조회수 날짜</div>
								<div class="divCont2">수정삭제버튼</div>
							</div>
							<div>내용</div>
							<div>댓글쓰기 textarea 등록버튼</div>
						</div>
					</div>
				</div>
				<div class="card">
					<div class="card-header">
						<a class="collapsed btn" data-bs-toggle="collapse" href="#collapseThree">
							게시판 글제목
						</a>
					</div>
					<div id="collapseThree" class="collapse" data-bs-parent="#accordion">
						<div class="card-body">
							<div class="divCont">
								<div class="divCont1">작성자 이메일 조회수 날짜</div>
								<div class="divCont2">수정삭제버튼</div>
							</div>
							<div>내용</div>
							<div>댓글쓰기 textarea 등록버튼</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	
	</body>
</html>

'대덕인재개발원 > 대덕인재개발원_Front End' 카테고리의 다른 글

231011_AJAX 강의  (0) 2023.10.11
231010_AJAX 강의  (0) 2023.10.10
231005_AJAX 강의  (0) 2023.10.05
231004_AJAX 강의  (0) 2023.10.02
230927_AJAX 강의  (0) 2023.09.27