MVC로 DB연결

문이빈·2023년 9월 8일
0

숙제)

URL의 요청 부분임 -> 뒤에 이런 주소가 들어오면 저 자바 파일로 보내라

------------------ControlServlet 수정------------------
Iterator it = properties.keySet().iterator();
	      while(it.hasNext()) {
	         String key = (String)it.next();
	         System.out.println("key = "+key);
	         
	         String className = properties.getProperty(key);
	         System.out.println("className = "+className);
	         
	         try {
	            Class<?> classType = Class.forName(className);
	            Object ob = classType.getConstructor().newInstance();
	            
	            System.out.println("ob = "+ob);
	            
	            map.put(key, ob);
	            
	         } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	         } catch (InstantiationException e) {
	            e.printStackTrace();
	         } catch (IllegalAccessException e) {
	            e.printStackTrace();
	         } catch (IllegalArgumentException e) {
	            e.printStackTrace();
	         } catch (InvocationTargetException e) {
				e.printStackTrace();
			 } catch (NoSuchMethodException e) {
				e.printStackTrace();
			 } catch (SecurityException e) {
				e.printStackTrace();
			 } 
	         
	         System.out.println();
	      }//while
	}

System.out.println("category = " + category); 
// category = /member/writeForm.do 
------------------loginOk 수정------------------

<h3>${sessionScope.memName }님이 로그인 하셨습니다.</h3>  
<%-- ${memName}를 써도 됨 -> page,session에서 언급한 적이 없어서 --%>

------------------writeForm 수정------------------

<form id = "memberWriteForm" method="post" action="/memberMVC/member/write.do">

<script type="text/javascript">
function checkID(){
//	var id = document.폼이름.name속성명.value;
//	var id = document.getElementById("id명").value;
	var id = document.getElementById("id").value;
	
	if(id =="")
		document.getElementById("idDiv").innerText = "먼저 아이디를 입력하세요.";
	else
		window.open("/memberMVC/member/checkId.do?id=" +id, 
        			"checkId", "width=400 height=150 top=300 left=700");
}

------------------checkIdOk 수정------------------

<body>
<form action="checkId.jsp">

<h3>${requestScope.id }는 사용 가능합니다.</h3>
<input type="button" value="사용하기" onclick="checkIdClose('${id}')" style="cursor: pointer">

</form>

<script type="text/javascript">
function checkIdClose(id){
	opener.document.getElementById("id").value = id;
	opener.document.getElementById("sw").value = id;
	window.close();
	opener.document.getElementById("pwd").focus();
}
</script>
</body>

------------------checkIdFail 수정------------------

<body>
<form action="/memberMVC/member/checkId.do">

<h3>${requestScope.id }는 이미 사용 중입니다.</h3>
<input type="submit" value="중복확인">

</form>

</body>

------------------CheckService.java 수정------------------

// 응답
		request.setAttribute("id", id);
		if(exist) { //exist가 true이면 이미 id가 있다는 것
			
			return "/member/checkIdFail.jsp";
		}else {

			return "/member/checkIdOk.jsp";
		}

writeForm 회원가입

sql, js 폴더 다 가져옴

------------------writeForm 수정------------------

<form id = "memberWriteForm" method="post" action="/memberMVC/member/write.do">
.
.
.
<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="../js/write.js"></script>

<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script src="../js/post.js"></script>

------------------command.properties 추가------------------

/member/write.do=member.service.WriteService

------------------WriteService.java------------------

package member.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.control.CommandProcess;

import member.bean.MemberDTO;
import member.dao.MemberDAO;

public class WriteService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {

		// 이미 가져와서 한글처리 안해도 됨
		
		// 데이터 
		String name = request.getParameter("name");
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		String gender = request.getParameter("gender");
		String email1 = request.getParameter("email1");
		String email2 = request.getParameter("email2");
		String tel1 = request.getParameter("tel1");
		String tel2 = request.getParameter("tel2");
		String tel3 = request.getParameter("tel3");
		String zipcode = request.getParameter("zipcode");
		String addr1 = request.getParameter("addr1");
		String addr2 = request.getParameter("addr2");

		MemberDTO memberDTO = new MemberDTO();
		memberDTO.setName(name);
		memberDTO.setId(id);
		memberDTO.setPwd(pwd);
		memberDTO.setGender(gender);
		memberDTO.setEmail1(email1);
		memberDTO.setEmail2(email2);
		memberDTO.setTel1(tel1);
		memberDTO.setTel2(tel2);
		memberDTO.setTel3(tel3);
		memberDTO.setZipcode(zipcode);
		memberDTO.setAddr1(addr1);
		memberDTO.setAddr2(addr2);
		
		// DB
		MemberDAO memberDAO = new MemberDAO();
		memberDAO.write(memberDTO);
		
		// 응답
		return "/member/write.jsp";
	}

}

------------------Write.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>회원 가입이 되었습니다.</h3>
<input type="button" value="로그인" onclick="location.href='/memberMVC/member/loginForm.do'">
</body>
</html>

글목록 MVC

------------------index.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>MVC기반의 게시판</h1>

<c:if test="${sessionScope.memId == null }">
<h3><a href="/boardMVC/member/loginForm.do">로그인</a></h3>
</c:if>

<c:if test="${sessionScope.memId != null }">
<h3><a href="/boardMVC/member/logout.do">로그아웃</a></h3>
<h3><a href="/boardMVC/board/boardWriteForm.do">글쓰기</a></h3>
</c:if>

<h3><a href="/boardMVC/board/boardList.do">목록</a></h3>

</body>
</html>

------------------command.properties------------------

# URL의 요청 부분 = JAVA파일

# 로그인
/member/loginForm.do=member.service.LoginFormService
/member/login.do=member.service.LoginService
/member/logout.do=member.service.LogoutService

# 게시판

## 글쓰기
/board/boardWriteForm.do=board.service.BoardWriteFormService
/board/boardWrite.do=board.service.BoardWriteService

## 목록
/board/boardList.do=board.service.BoardListService
/board/boardView.do=board.service.BoardViewService

------------------Write.jsp------------------
package member.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.control.CommandProcess;

public class LoginFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/loginForm.jsp";
   }
}
------------------loginForm.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse:collapse;
}

#memberloginForm div{
	font-size: 8pt;
	font-weight: bold;
	color: red;
}
</style>
</head>
<body>
<form id="memberloginForm" method="post" action="/boardMVC/member/login.do">
	<table border="1" cellspacing ="0" cellpadding ="7">
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" id="id" name="id" placeholder="아이디 입력" size="30">
				<div id="idDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>비밀번호</th>
			<td >
				<input type="password" id="pwd" name="pwd" size="40">
				<div id="pwdDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th colspan="2">
				<button type="button" id="loginBtn">로그인</button>
				<button type="button" onclick="location.href='writeForm.jsp'">회원가입</button>
			</th>
		</tr>
	</table>
</form>

<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function(){
	$('#loginBtn').click(function(){
		$('#idDiv').empty();
		$('#pwdDiv').empty();
		
		if($('#id').val()==''){
			$('#idDiv').text('아이디를 입력하세요.');
			$('#id').focus();
			
		}else if($('#pwd').val()==''){
			$('#pwdDiv').text('비밀번호를 입력하세요.');
			$('#pwd').focus();
			
		}else{
			$('#memberloginForm').submit();
		}
	});
});
</script>
</body>
</html>

------------------loginFormService.java------------------

package member.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.control.CommandProcess;

public class LoginFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/loginForm.jsp";
   }
}

------------------loginOk.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h3>${name }님이 로그인 하셨습니다.</h3>  <%-- ${memName}를 써도 됨 -> page,session에서 언급한 적이 없어서 --%>

<input type="button" value="로그아웃" onclick="location.href='/boardMVC/member/logout.do'">
<input type="button" value="글쓰기" onclick="location.href='/boardMVC/board/boardWriteForm.do'">

</body>
</html>

------------------boardWirteForm.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse: collapse;
	padding: 10px;
}
#content{
	width: 300px;
	height: 400px;
}
#subjectDiv {
	color: red;
}
#contentDiv{
	color: red;
}
</style>
</head>
<body>
<form id = "boardWriteForm" method="post" action="/boardMVC/board/boardWrite.do">
<h3>글쓰기</h3>
	<table border="1" cellspacing ="0" cellpadding ="5">
		<tr>
			<th width="100" align ="center">글제목</th>
			<td>
				<input type="text" id="subject" name="subject">
				<div id="subjectDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>글내용</th>
			<td>
				<textarea id="content" name="content" rows="10" cols="40"></textarea>
				<div id="contentDiv"></div>
			</td>
		</tr>

		<tr>
			<td colspan="2" align="center">
				<input type="button" id="writeBtn" value="글쓰기">
				<input type="reset" value="다시작성">
				<input type="button" value="목록" onclick="location.href='boardList.do'">
			</td>
		</tr>
	</table>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.0.min.js"></</script>
<script src="../js/boardWrite.js"></script>
</body>
</html>

------------------boardWrite.js------------------

$(function(){
		$('#writeBtn').click(function(){
		$('#subjectDiv').empty();
		$('#contentDiv').empty();
		
		if($('#subject').val()==''){
			$('#subjectDiv').text('제목을 입력하세요.');
			$('#subject').focus();
			
		}else if($('#content').val()==''){
			$('#contentDiv').text('내용을 입력하세요.');
			$('#content').focus();
			
		}else{
			//$('#boardWriteForm').submit();
			
			$.ajax({   // boardWrite에 갔다 와라 - 항상 이 자리로 돌아와라 -> 화면이동 없음
				type: 'post', // boardWriteForm에 method를 post방식을 빼버려도됨
				url: '/boardMVC/board/boardWrite.do',
				data: {
					'subject': $('#subject').val(),
					'content': $('#content').val()
				},
				success: function(){
					alert("작성하신 글을 저장하였습니다.");
					location.href='boardList.jsp?pg=1';
				},
				error: function(){
					console.log(e);
				}
			}); 
			
		}
	});
});

------------------boardWriteFormService.java------------------

package board.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.control.CommandProcess;

public class BoardWriteFormService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {

		return "/board/boardWriteForm.jsp";
	}

}

------------------boardWrite.java------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript">
window.onload=function(){
	alert("작성하신 글이 등록되었습니다.");
	
	// 목록
	location.href="/boardMVC/board/boardList.do?pg=1";
}
</script>

</body>
</html>

------------------boardWriteService.java------------------

package board.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.control.CommandProcess;

import board.dao.BoardDAO;

public class BoardWriteService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {
		
		//데이터
		String subject = request.getParameter("subject");
		String content = request.getParameter("content");

		HttpSession session = request.getSession(); // 세션 생성
		String id = (String)session.getAttribute("memId");
		String name = (String)session.getAttribute("memName");
		String email = (String)session.getAttribute("memEmail");

		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		map.put("name", name);
		map.put("email", email);
		map.put("subject", subject);
		map.put("content", content);


		//DB
		BoardDAO boardDAO = new BoardDAO();
		boardDAO.boardWrite(map);
		
		return "/board/boardWrite.jsp";
	}

}

------------------boardList.jsp------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse: collapse;
}
th, td{
  padding: 5px;
}
#currnetPaging{
	border: 1px solid #ccc;
	margin: 5px;
	padding: 8px;
	color: red;
	cursor: pointer;
}
#paging{
	color: black;
	margin: 5px;
	padding: 5px;
	cursor: pointer;
}
.subjectA:link{color : black; text-decoration: none;}
.subjectA:visited{color : black; text-decoration: none;}
.subjectA:hover{color : green; text-decoration: underline;}
.subjectA:active{color : black; text-decoration: none;}
</style>
</head>
<body>

<c:if test="${requestScope.list != null}">

<table border="1" frame="hsides" rules="rows">

		<tr>
			<th width="100">글번호</th>
			<th width="400">제목</th>
			<th width="150">작성자</th>
			<th width="150">작성일</th>
			<th width="100">조회수</th>
		</tr>

<c:forEach var="boardDTO" items="${list}">
		<tr>
	        <td align="center">${boardDTO.seq }</td>
	        <td>
	        	<a class="subjectA" href="javascript:void(0)" style="cursor: pointer" 
	        	   onclick="isLogin('${boardDTO.id }', ${boardDTO.seq }, ${pg})">${boardDTO.subject }
	        		
	        	</a>
	        </td>
	        <td align="center">${boardDTO.id }</td>
	        <td align="center"><fmt:formatDate value="${boardDTO.lgotime }" pattern="yyyy.MM.dd." type="date"/></td>
	        <td align="center">${boardDTO.hit }</td>
		</tr>
</c:forEach>

</table>
<input type="button" value="목록" onclick="location.href='boardList.jsp'">

<div style="width: 900px; text-align: center;">
${ boardPaging.pagingHTML }
</div>

</c:if>

<script type="text/javascript">
function boardPaging(pg){
	location.href = "boardList.do?pg=" + pg;
}

function isLogin(id,seq,pg){
	if(id == 'null')
		alert("먼저 로그인하세요");
	else
		location.href="boardView.do?seq=" + seq + "&pg=" + pg;
}
</script>
</body>
</html>

------------------boardListService.java------------------

package board.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.control.CommandProcess;

import board.bean.BoardDTO;
import board.bean.BoardPaging;
import board.dao.BoardDAO;

public class BoardListService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {
		
		// 데이터
		int pg = Integer.parseInt(request.getParameter("pg"));

		// 1페이지당 5개씩만 꺼내올거임
		int endNum = pg*5;
		int startNum = endNum-4;

		// DB
		BoardDAO boardDAO = new BoardDAO();
		List<BoardDTO> list = boardDAO.getBoardList(startNum, endNum);

		//페이징 처리
		int totalA = boardDAO.getTotalA(); // 총 글수 select count(*) from board; 

		BoardPaging boardPaging = new BoardPaging();
		boardPaging.setCurrentPage(pg);
		boardPaging.setPageBlock(3);
		boardPaging.setPageSize(5);
		boardPaging.setTotalA(totalA);

		boardPaging.makePagingHTML();

		// 세션
		HttpSession session = request.getSession(); 
		String id = (String)session.getAttribute("memId");
		
	
		//응답
		request.setAttribute("list", list);
		request.setAttribute("pg", pg);
		request.setAttribute("boardPaging", boardPaging);
		
		return "/board/boardList.jsp";
	}
}

나머지는 나중..

0개의 댓글