1차 프로젝트 마무리 , 문서작성

 

Git에 전부 올려 둠

https://github.com/cojuns/choongang/tree/master/1%EC%B0%A8_%EA%B0%9C%EC%9D%B8%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8

 

 

계획안 작성 해보기

 

 

수행 결과 작성 해보기 PPT ( 기능 구현 내용, 동영상 시연 ) 

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-08-23 67일차  (0) 2023.08.23
2023-08-22 66일차  (0) 2023.08.23
2023-08-18 64일차  (0) 2023.08.20
2023-08-17 63일차  (0) 2023.08.17
2023-08-16 62일차  (0) 2023.08.16

1차 프로젝트 

패스워드 변경 수정

 

Controller

	@GetMapping("/changePwd.do")
	public String changePwd1() {
		return "changePwdForm";
	}
	

	
	
	@PostMapping("/changePwd.do")
	@ResponseBody
	public String changePassword(@RequestParam String curPwd, @RequestParam String newPwd, HttpSession session) {
	    User user = (User) session.getAttribute("authUser"); // 로그인된 사용자 정보

	    Member storedMember = memberDao.selectById(user.getId());

	    if (!storedMember.matchPassword(curPwd)) {
	        return "badCurPwd"; // 현재 비밀번호 불일치 시 에러 반환
	    }

	    try {
	        changePwdSvc.changePassword(user.getId(), curPwd, newPwd);
	        return "success"; // 비밀번호 변경 성공 시 성공 반환
	    } catch (InvalidPasswordException e) {
	        return "error"; // 비밀번호 변경 실패 시 에러 반환
	    } catch (MemberNotFoundException e) {
	        return "error"; // 사용자 정보를 찾을 수 없을 때 에러 반환
	    }
	}

 

자바스크립트 ( Ajax )

$(document).ready(function() {
    $("#changePw").click(function(event) {
        event.preventDefault();
        
        var curPwd = $("#curPwd").val();
        var newPwd = $("#newPwd").val();
        
        $(".error-message").text(""); // 기존 오류 메시지 초기화
        
        if (!curPwd) {
            $("#curPwdError").text("현재 암호를 입력하세요.");
            return;
        }
        if (!newPwd) {
            $("#newPwdError").text("새 암호를 입력하세요.");
            return;
        }
        
        // 서버로 비밀번호 변경 요청 보내기
        $.ajax({
            type: "POST",
            url: "changePwd.do",
            data: { curPwd: curPwd, newPwd: newPwd },
            
            success: function(response) {
                if (response === "badCurPwd") {
                    $("#curPwdError").text("현재 암호가 일치하지 않습니다.");
                } else {
                    alert("암호변경을 완료했습니다.");
                    // 성공적으로 변경되었으면 페이지 이동
                    window.location.href = "index.jsp";
                }
            },
            
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
                alert("암호 변경 실패: " + status);
            }
        });
    });
});

 

 

 

JSP

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>암호 변경</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>

<div class="login-box">
<form action="changePwd.do" method="post">
<div class="user-box">
    <p>
        <label>현재 암호:</label><br/>
        <input type="password" name="curPwd" id="curPwd">
        <span id="curPwdError" class="error-message"></span>
    </p>
</div>


<div class="user-box">
<p>
    <label>새 암호:</label><br/><input type="password" name="newPwd" id="newPwd">
    <span id="newPwdError" class="error-message"></span>
</p>
</div>

    <div style="display: flex; justify-content: center;">
    <button class="buttonS" id="changePw">암호변경
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>
	
	
	</div>
</form>
</div>

</body>
</html>

 

 

 

 

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-08-22 66일차  (0) 2023.08.23
2023-08-21 65일차  (0) 2023.08.21
2023-08-17 63일차  (0) 2023.08.17
2023-08-16 62일차  (0) 2023.08.16
2023-08-11 61일차  (0) 2023.08.11

1차 프로젝트 

 

login

 

jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>로그인</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">

</head>
<body>

<div class="login-box">
<form action="login.do" method="post">
<c:if test="${errors.idOrPwNotMatch}">
<h5>아이디와 암호가 일치하지 않습니다.</h5>
</c:if>
<div class="user-box">
<p>
	<label>아이디:</label><br/>
	<c:if test="${errors.id}"><h5>ID를 입력하세요.</h5></c:if>
	<input type="text" name="id" value="${param.id}">
	
</p>
</div>

<div class="user-box">
<p>
	<label>암호:</label><br/>
	<c:if test="${errors.password}"><h5>암호를 입력하세요.</h5></c:if>
	<input type="password" name="password">
	
</p>
</div>
    <div style="display: flex; justify-content: center;">
    <button class="buttonS">로그인
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>
	
	
	</div>
</form>

</div>

</body>
</html>

 

 

changePwd

JSP

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>암호 변경</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>

<div class="login-box">
<form action="changePwd.do" method="post">
<div class="user-box">
<p>
	<label>현재 암호:</label><br/><input type="password" name="curPwd">
	<c:if test="${errors.curPwd}">현재 암호를 입력하세요.</c:if>
	<c:if test="${errors.badCurPwd}"><h5>현재 암호가 일치하지 않습니다.</h5></c:if>
</p>
</div>

<div class="user-box">

<p>
	<label>새 암호:</label><br/><input type="password" name="newPwd">
	<c:if test="${errors.newPwd}">새 암호를 입력하세요.</c:if>
</p>


</div>

    <div style="display: flex; justify-content: center;">
    <button class="buttonS" id="changePw">암호변경
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>
	
	
	</div>
</form>
</div>

</body>
</html>

 

list 게시판

jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>게시글 목록</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">

</head>
<body>
<div class="login-box">

<table class= "tables">

	<tr>
		<td>번호</td>
		<td>제목</td>
		<td>작성자</td>
		<td>작성일자</td>
		<td>조회수</td>
	</tr>
	
<c:if test="${articlePage.hasNoArticles()}">
	<tr>
		<td colspan="4">게시글이 없습니다.</td>
	</tr>
</c:if>
<c:forEach var="article" items="${articlePage.content}">
	<tr>
		<td>${article.number}</td>
		
		<td>
		<a href="read.do?no=${article.number}&pageNo=${articlePage.currentPage}">
		<c:out value="${article.title}"/>
		
		</a>
		</td>
		
		
		<td>${article.writer.name}</td>
		<td>${article.regDate}</td>
		<td>${article.readCount}</td>
	</tr>
</c:forEach>
	
	<tr>
		<td colspan="4">
		<div class="buttons">
		<a href="write.do">[게시글쓰기]
		
		</a>
		</div>
		</td>
	</tr>

<div class= "pages" >
<c:if test="${articlePage.hasArticles()}">
	<tr>
		<td colspan="4">
			<c:if test="${articlePage.startPage > 5}">
			<a href="list.do?pageNo=${articlePage.startPage - 5}">[이전]</a>
			</c:if>
			<c:forEach var="pNo" 
					   begin="${articlePage.startPage}" 
					   end="${articlePage.endPage}">
			<a href="list.do?pageNo=${pNo}">[${pNo}]</a>
			</c:forEach>
			<c:if test="${articlePage.endPage < articlePage.totalPages}">
			<a href="list.do?pageNo=${articlePage.startPage + 5}">[다음]</a>
			</c:if>
		</td>
	</tr>
</c:if>
</div>

</table>
</div>

</body>
</html>

 

modify 게시판

jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>게시글 수정</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css?ver=1.3">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>

<div class="login-box">
<form action="modify.do" method="post">
<input type="hidden" name="no" value="${modReq.articleNumber}">
<p>
	<label>번호:</label><br/>${modReq.articleNumber}
</p>
<p>
	<label>제목:</label><br/><input type="text" name="title" value="${modReq.title}">
	<c:if test="${errors.title}">제목을 입력하세요.</c:if>
</p>
<p>
	<label>내용:</label><br/>
	<textarea name="content" rows="5" cols="30">${modReq.content}</textarea>
</p>


    <button class="buttonS" id="modify">글 수정
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>


</form>
</div>

</body>
</html>

js  ( ajax 수정 후 알럿 띄우고 list.do로 이동 ) 

$(document).ready(function() {
    $("#modify").click(function(event) {
        event.preventDefault(); // 기본 동작 중단

        // 입력값 확인
        var title = $("input[name='title']").val();
        var content = $("textarea[name='content']").val(); // textarea 입력값 가져오기
        
        if (title === "" || content === "") {
            alert("빈 칸을 모두 입력하세요.");
            return;
        }

        // 회원가입 데이터를 서버로 전송
        $.ajax({
            type: "POST",
            url: "modify.do",
            data: $("form").serialize(),
            success: function(response) {
               
                alert("수정이 완료되었습니다.");
                
                window.location.href = "list.do"; 
            },
            error: function(xhr, status, error) {
                alert("회원가입 중 오류가 발생했습니다. 다시 시도해주세요.");
            }
        });
    });
});

 

 

read 게시판 

jsp ( 게시글삭제 클릭 시 사용자에게 삭제 여부 확인 후 ajax로 이동해서 삭제 알럿 띄우고 list.do로 이동 )  

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="u" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>
<title>게시글 읽기</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>
<div class="login-box">
<table class= "tables">

<tr>
	<td>번호</td>
	<td>작성자</td>
	<td>제목</td>
	<td>내용</td>
	
</tr>

<tr>
	<td>${articleData.article.number}</td>
	<td>${articleData.article.writer.name}</td>
	<td><c:out value='${articleData.article.title}' /></td>
	<td><u:pre value='${articleData.content}'/></td>

</tr>


<tr>
	<td colspan="2">
		<c:set var="pageNo" value="${empty param.pageNo ? '1' : param.pageNo}" />
		<a href="list.do?pageNo=${pageNo}">[목록]</a>
		<c:if test="${authUser.id == articleData.article.writer.id}">
		<a href="modify.do?no=${articleData.article.number}">[게시글수정]</a>
		<a class="delete-link" data-article-no="${articleData.article.number}">[게시글삭제]</a>
		</c:if>
	</td>
</tr>


</table>
</div>

</body>
</html>

js ( delete )

$(document).ready(function() {
    $(".delete-link").click(function(event) {
        event.preventDefault();
        var articleNo = $(this).data("article-no");
        var con = confirm("정말로 이 글을 삭제하시겠습니까?");
        
        if (con) {
            $.ajax({
                type: "GET",
                url: "delete.do",
                data: { no: articleNo },
                success: function(response) {
                    alert("글이 삭제되었습니다.");
                     window.location.href = "list.do";
                    // 삭제된 게시글을 목록에서 제거하거나 다시 불러오는 등의 처리
                    // 예를 들어, 아래와 같이 삭제된 행을 제거할 수 있습니다.
                    // $("#article-" + articleNo).remove();
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert("글 삭제 실패: " + textStatus);
                }
            });
        }
    });
});

 

 

write 게시물 작성

jsp 

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>게시글 쓰기</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css?ver=1.3">

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>
<div class="login-box">
<form action="write.do" method="post">

<p>
	<label>제목:</label><br/><input type="text" name="title" value="${param.title}">
	<c:if test="${errors.title}">제목을 입력하세요.</c:if>
</p>
<p>
	<label>내용:</label><br/>
	<textarea name="content" rows="5" cols="30">${param.title}</textarea>
	
</p>


    <button class="buttonS" id="writes">등록
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>

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

js ( 게시물 작성완료되면 알럿 띄우고 list.do로 이동 )

/*게시물 작성*/
$(document).ready(function() {
    $("#writes").click(function(event) {
        event.preventDefault();
        
        var title = $("input[name='title']").val();
        var content = $("textarea[name='content']").val();
        
        
             if (title === "") {
            alert("제목을 입력하세요.");
            return;
        }
              if (content === "") {
            alert("내용을 입력하세요.");
            return;
        }
        
           if (title === "" || content === "") {
            alert("빈 칸 모두 입력하세요.");
            return;
        }
        
        $.ajax({
            type: "POST",
            url: "write.do",
            data: { title: title, content: content },
            
            
            success: function(response) {
			console.log(response);
   
                    alert("게시글이 등록되었습니다.");
                    // 성공적으로 등록되었으면 페이지 이동
                    window.location.href = "list.do";
                
            },
            
        });
    });
});

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-08-21 65일차  (0) 2023.08.21
2023-08-18 64일차  (0) 2023.08.20
2023-08-16 62일차  (0) 2023.08.16
2023-08-11 61일차  (0) 2023.08.11
2023-08-10 60일차  (0) 2023.08.10

1차 프로젝트 스타트 ( 회원가입, 로그인, 게시판 ) 

스프링MVC, JDBC 템플릿 ( 추후 시간되면 마이바티스로 변경 예정 ), 메이븐,

 

1. index.jsp ( 메인 ) 

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="u" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">
<title>회원제 게시판 예제</title>
</head>
<body>
<%-- 
<c:if test="${! empty authUser}">
	${authUser.name}님, 안녕하세요.
	<a href="logout.do">[로그아웃하기]</a>
	<a href="changePwd.do">[암호변경하기]</a>
</c:if>
<c:if test="${empty authUser}">
	<a href="join.do">[회원가입하기]</a>
	<a href="login.do">[로그인하기]</a>
</c:if>
--%>
<u:isLogin>
	
	<div class="login-box">
  <h2>${authUser.name}님, 안녕하세요.</h2>
  <form>


    <div class="buttons">
    <a href="logout.do">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      로그아웃
    </a>
        <a href="changePwd.do">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      암호변경
    </a>

	     <a href="article/list.do">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      게시판
    </a>
	
    </div>
    

    </div>
    
    
  </form>
  



</div>

	
	
	
</u:isLogin>



<u:notLogin>
	
	<div class="login-box">
  <h2>Main</h2>
  <form>


    <div class="buttons">
    <a href="join.do">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      회원가입
    </a>
        <a href="login.do">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      로그인하기
    </a>
    </div>
  </form>
  





</div>

	
</u:notLogin>
<br/>
</body>
</html>

 

처음 notLogin tag 부분 실행 ( 회원가입, 로그인 )

로그인 완료되면 isLogin tag 부분 실행 로그인한 user 이름 출력, 로그아웃, 암호변경, 게시판이동 

밑에는 tags 폴더 파일들

isLogin.tag

<%@ tag body-content="scriptless" pageEncoding="utf-8" %>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:if test="${not empty sessionScope.authUser}">
    <jsp:doBody />
</c:if>

 

notLogin.tag

<%@ tag body-content="scriptless" pageEncoding="utf-8" %>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:if test="${empty sessionScope.authUser}">
    <jsp:doBody />
</c:if>

 

pre.tag

<%@ tag body-content="empty" pageEncoding="utf-8" %>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ attribute name="value" type="java.lang.String" required="true"%>
<%
	value = value.replace("&", "&amp;");
	value = value.replace("<", "&lt;");
	value = value.replace(" ", "&nbsp;");
	value = value.replace("\n", "\n<br>");
%>
<%= value %>

 

 

2. join.jsp ( 회원가입)

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>가입</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/js.js"></script>

</head>
<body>
<div class="login-box">
<form action="join.do" method="post">
<div class="user-box">
    <p>
        <label>아이디</label><br/>
        <input type="text" name="id" value="${param.id}" id="id" placeholder="아이디">
        <input type="button" id="checkId" value="중복검사" class="buttonC">
        <div id="result_checkId" style="font-size:12px;"></div>
    </p>
</div>
<div class="user-box">
<p>
	<label>이름</label><br/><input type="text" name="name" value="${param.name}">
	<c:if test="${errors.name}">이름을 입력하세요.</c:if>
</p>
</div>
<div class="user-box">
<p>
	<label>패스워드</label><br/><input type="password" name="password" id="password">
	<c:if test="${errors.password}">암호를 입력하세요.</c:if>
</p>
</div>
<div class="user-box">
<p>
	<label>패스워드 확인</label><br/><input type="password" name="confirmPassword">
	<c:if test="${errors.confirmPassword}">확인을 입력하세요.</c:if>
	<c:if test="${errors.notMatch}"><h4>암호가 일치하지 않습니다.</h4></c:if>
	<c:if test="${errors.duplicateId}"><h4>이미 사용중인 아이디입니다.</h4></c:if>
</p>
</div>

    <div style="display: flex; justify-content: center;">
    <button class="buttonS">가입
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      </button>
	
	
	</div>

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

 

회원가입 Ajax ( 빈칸 확인, 비밀번호 일치 여부, 중복 검사 후 가입 가능 기능 등 )

중요한 건 Ajax로 DB에서 memberid값을 count(*)로 해서 값이 1이면 중복, 값이 0이면 사용 가능 

/*가입완료*/
$(document).ready(function() {
    $(".buttonS").click(function(event) {
        event.preventDefault(); // 기본 동작 중단

        // 입력값 확인
        var id = $("input[name='id']").val();
        var name = $("input[name='name']").val();
        var password = $("input[name='password']").val();
        var confirmPassword = $("input[name='confirmPassword']").val();

        if (id === "" || name === "" || password === "" || confirmPassword === "") {
            alert("빈 칸을 모두 입력하세요.");
            return;
        }

        if (password !== confirmPassword) {
            alert("비밀번호가 일치하지 않습니다.");
            return;
        }

        // 중복 검사 결과 확인
        var result_checkId = $("#result_checkId").text();
        if (result_checkId !== "사용 가능한 아이디입니다.") {
            alert("아이디 중복 검사 후 가입 버튼을 눌러주세요.");
            return;
        }

        // 회원가입 데이터를 서버로 전송
        $.ajax({
            type: "POST",
            url: "join.do",
            data: $("form").serialize(),
            success: function(response) {
                // 회원가입 완료 후 알림 표시
                alert("회원가입이 완료되었습니다. 로그인 페이지로 이동합니다.");
                // 로그인 페이지로 이동
                window.location.href = "login.do"; // 로그인 페이지 경로로 수정하세요.
            },
            error: function(xhr, status, error) {
                alert("회원가입 중 오류가 발생했습니다. 다시 시도해주세요.");
            }
        });
    });
		/*아이디 중복 검사*/
    $("#checkId").click(function() {
        let id = $("#id").val();
        
                if (id === "") {
            alert("아이디를 입력해주세요.");
            return;
        }
        
        $.ajax({
            type: 'post',
            url: "checkId.do", // 컨트롤러로 가는 mapping 입력
            data: { "id": id },
            dataType: "json",
            success: function(data) { 
                if (data.status === "N") {
                    result = "사용 가능한 아이디입니다.";
                    $("#result_checkId").html(result).css("color", "green");
                    $("#password").trigger("focus");
                } else {
                    result = "이미 사용중인 아이디입니다.";
                    $("#result_checkId").html(result).css("color", "red");
                    $("#id").val("").trigger("focus");
                }
            },
            error: function(error) {
                alert("error: " + error);
            }
        });
    });
});

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-08-18 64일차  (0) 2023.08.20
2023-08-17 63일차  (0) 2023.08.17
2023-08-11 61일차  (0) 2023.08.11
2023-08-10 60일차  (0) 2023.08.10
2023-08-09 59일차  (0) 2023.08.09

마이바티스 스프링 설정

pom.xml 중요한 부분은 resources

		<resources>
			<resource>
				<directory>src/resources</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
				</includes>
				<filtering>false</filtering>
			</resource>
		</resources>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>board</groupId>
	<artifactId>board</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jdbc</artifactId>
			<version>8.5.27</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.33</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.25</version>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.2.3</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-maven-plugin -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok-maven-plugin</artifactId>
			<version>1.18.20.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.2-b02</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.5</version>
		</dependency>
		
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		
		<resources>
			<resource>
				<directory>src/resources</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
				</includes>
				<filtering>false</filtering>
			</resource>
		</resources>
		
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>11</source>
					<target>11</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

해당 위치 처럼 패키지, xml파일 설정 

 

config-mybatis.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>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

	<mappers>
		<!-- 마이바티스 매퍼 XML 파일 -->
		<mapper resource="mapper/MemberMapper.xml" />
	</mappers>
	
</configuration>

 

MemberMapper.xml

해당 파일에 쿼리문 작성 후 인터페이스에 지정

#{PARAM1}같은 건 ? 대신 사용 PARAM1은 아무거나 써도 됨 

<?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="mybatis.dao.MemberDAO">
    <select id="selectCount" resultType="_int">
        SELECT count(*)
        FROM member
    </select>
    
    <select id="selectList" resultType="member.model.Member">
        SELECT *
        FROM member
    </select>
    
    <select id="selectById" parameterType="string" resultType="member.model.Member">
    	SELECT * FROM MEMBER WHERE MEMBERID = #{PARAM1}
    </select>
    
    <update id="updateArtilce">
    	update article set title = #{param1}, moddate = now()
				where article_no = #{param2}
    
    </update>
    
    <insert id="insertArtCont" parameterType="article.model.ArticleContent">
    insert into article_content(article_no, content) values(#{artCon.number}, #{artCon.content});

    </insert>
    
    <insert id="insertArticle" parameterType="article.model.Article"
    									useGeneratedKeys="true" keyProperty="number">
    	insert into article(writer_id, writer_name, title, regdate, moddate, read_cnt)
			values (#{art.writer.id},#{art.writer.name},#{art.title},now(),now(),0)
    
    </insert>
    
</mapper>

 

mybatis.dao 패키지안에 MemberDAO 인터페이스 생성

MemberMapper.xml 참고해서 만들기

 

 

 

package mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import article.model.Article;
import article.model.ArticleContent;
import member.model.Member;

@Mapper
public interface MemberDAO {
	
	@Select("select * from member")
	List<Member> selectAll();
	
	Integer selectCount();
	
	List<Member> selectList();
	
	Member selectById(String id);
	
	void updateArtilce(String title, int num);
	
	void insertArtCont(@Param("artCon") ArticleContent articleContent);
	
	void insertArticle(@Param("art") Article article);
}

 

스프링 config에 MapperScan + SqlSessionFactory 설정

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "mybatis.dao")
public class ControllerConfig {
	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		DataSource ds = new DataSource();
		ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/board?" + "useSSL=true&useUnicode=true&characterEncoding=utf8");
		ds.setUsername("jspexam");
		ds.setPassword("jsppw");
		ds.setInitialSize(2);
		ds.setMaxActive(10);
		return ds;
	}


	@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:config-mybatis.xml"));
        //factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/**/*.xml"));
        factoryBean.setTypeAliasesPackage("mybatis.dao");
        return factoryBean.getObject();
    }
	
//	@Bean // 필요할 때 사용 
//	public SqlSessionFactory sqlSessionFactory() throws Exception {
//		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
//		sqlSessionFactory.setDataSource(dataSource());
//		return (SqlSessionFactory) sqlSessionFactory.getObject();
//	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory());
	}

 

마이바티스 테스트

package controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import article.dao.ArticleContentDao;
import article.dao.ArticleDao;
import auth.service.LoginService;
import member.dao.MemberDao;
import member.model.Member;
import member.service.ChangePasswordService;
import mybatis.dao.MemberDAO;

@Controller
public class MyController {
	@Autowired
	private ArticleContentDao articleContentDao;
	@Autowired
	private ArticleDao articleDao;
	
	@Autowired
	private MemberDAO memberDAO; 
	
	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private ChangePasswordService changePasswordService;
	
	@GetMapping("/count")
	public String countMember() {
		
		 마이바티스 테스트
		List<Member> list = memberDAO.selectAll();
		System.out.println(list);
		
		System.out.println(memberDAO.selectCount());
		
		List<Member> list = memberDAO.selectList();
		for(Member member : list) {
		System.out.println(member);	
		}
		
		Member member = memberDAO.selectById("test3");
		System.out.println(member);
		
		memberDAO.updateArtilce("글제목 369", 12);
		
		ArticleContent artc1 = new ArticleContent(105, "김기철");
		memberDAO.insertArtCont(artc1);
		
		Writer wr = new Writer("test34", "홍길동34");
		Article art = new Article(0, wr, "홍길동 테스트", null, null, 0);
		memberDAO.insertArticle(art);
//		System.out.println(art);

 

 

 

스프링5 MVC 게시판 

 

DAO

 

ArticleContentDao

package article.dao;

import java.util.List;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import article.model.ArticleContent;

public class ArticleContentDao {

	private JdbcTemplate jdbcTemplate;
	
	public ArticleContentDao(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	// 게시물 내용을 삽입
	public ArticleContent insert(ArticleContent content) { 
		String sql = "insert into article_content (article_no, content) values (?,?)";
		int insertedCount 
		 = jdbcTemplate.update(sql, content.getNumber(),content.getContent());
			

			if (insertedCount > 0) {
				return content;
			} else {
				return null;
			}
	}
	// 특정 ID에 해당하는 게시물 내용을 조회
	public ArticleContent selectById(int no){
		String sql = "select * from article_content where article_no = ?";
		List<ArticleContent> list = jdbcTemplate.query(sql, (rs, n)->{
			return new ArticleContent(
					rs.getInt("article_no"),
					rs.getString("content"));
		},no);
		return list.isEmpty() ? null : list.get(0);

	}
	
	// 특정 ID에 해당하는 게시물 내용을 업데이트
	public int update(int no, String content) {
		String sql = "update article_content set content = ? where article_no = ?";
		return jdbcTemplate.update(sql, content, no);
		

	}

}

 

 

ArticleDao

package article.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import article.model.Article;
import article.model.Writer;

public class ArticleDao {
	
	private JdbcTemplate jdbcTemplate;
	
	public ArticleDao(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

//	public Article insert(Article article) {
//		
//		String sql = "insert into article"
//				+ "(writer_id, writer_name, title, regdate, moddate, read_cnt)"
//				+ "values (?,?,?,now(),now(),0)";
//		int insertedCount = jdbcTemplate.update(sql, article.getWriter().getId(),
//													 article.getWriter().getName(),
//													 article.getTitle());
//		if (insertedCount > 0) {// 스프링 197페이지
//			int num = jdbcTemplate.queryForObject("select last_insert_id()"
//													, Integer.class);
//			article.setNumber(num);
//			return article;
//		}return null;
//				
//	}
	
	// 게시물 추가 메서드
	// 201~203쪽 keyHolder, 람다식
	public Article insert(Article article) {
	
	String sql = "insert into article"
			+ "(writer_id, writer_name, title, regdate, moddate, read_cnt) values (?,?,?,now(),now(),0)";
	
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update((con) -> {
		PreparedStatement pstm = con.prepareStatement(sql, new String[] {"article_no"});
		pstm.setString(1, article.getWriter().getId());
		pstm.setString(2, article.getWriter().getName());
		pstm.setString(3, article.getTitle());
		return pstm;
	},keyHolder);
	// 자동 생성된 키 값 가져오기 및 설정
	Number keyvalue = keyHolder.getKey();
	article.setNumber(keyvalue.intValue());
	return article;
	

			
}
	
	
	
	
    // 전체 게시물 개수 조회
	private Timestamp toTimestamp(Date date) {
		return new Timestamp(date.getTime());
	}

	public int selectCount()  {
		
		String sql = "select count(*) from article";
		
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}
	
	// 특정 범위의 게시물 목록 조회
	public List<Article> select(int startRow, int size) {
		
		String sql = "select * from article order by article_no desc limit ?, ?";
		
		return jdbcTemplate.query(sql,
				(rs, n)-> convertArticle(rs), startRow, size);

	}
	// ResultSet을 Article 객체로 변환
	private Article convertArticle(ResultSet rs) throws SQLException {
		return new Article(rs.getInt("article_no"),
				new Writer(
						rs.getString("writer_id"),
						rs.getString("writer_name")),
				rs.getString("title"),
				toDate(rs.getTimestamp("regdate")),
				toDate(rs.getTimestamp("moddate")),
				rs.getInt("read_cnt"));
	}
	
	
	// Timestamp를 Date로 변환
	private Date toDate(Timestamp timestamp) {
		return new Date(timestamp.getTime());
	}
	
	
	// 특정 ID에 해당하는 게시물 조회
	public Article selectById(int no)  {
		
		String sql = "select * from article where article_no = ?";
		
		List<Article> list = jdbcTemplate.query(sql,
				(rs, n) -> convertArticle(rs), no);
		
		return list.isEmpty() ? null : list.get(0);
		

	}
	  // 게시물의 조회수 증가
	public void increaseReadCount(int no) {
		String sql = "update article set read_cnt = read_cnt + 1 where article_no = ?";
		jdbcTemplate.update(sql, no);
		

	}
	 // 게시물 정보 업데이트 메서드
	public int update(int no, String title) {
		String sql = "update article set title = ?, moddate = now() where article_no = ?";
		
		return jdbcTemplate.update(sql, title, no);

	}
	// 게시물 삭제 메서드
	public int delete(int no) {
		String sql = "delete from article where article_no =?";
		return jdbcTemplate.update(sql, no);
	}
	
	
}

 

 

Service ( 종류가 많아서 GitHub 주소 참고 )

 

 

Config 

package config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import article.dao.ArticleContentDao;
import article.dao.ArticleDao;
import article.service.ListArticleService;
import article.service.ModifyArticleService;
import article.service.ReadArticleService;
import article.service.WriteArticleService;
import auth.service.LoginService;
import controller.ArtController;
import controller.LogController;
import controller.MyController;
import member.dao.MemberDao;
import member.service.ChangePasswordService;
import member.service.JoinService;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "mybatis.dao")
public class ControllerConfig {
	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		DataSource ds = new DataSource();
		ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/board?" + "useSSL=true&useUnicode=true&characterEncoding=utf8");
		ds.setUsername("jspexam");
		ds.setPassword("jsppw");
		ds.setInitialSize(2);
		ds.setMaxActive(10);
		return ds;
	}

	@Bean
	public MemberDao memberDao() {
		return new MemberDao(dataSource());
	}

	@Bean
	public LoginService loginService() {
		return new LoginService();
	}

	@Bean
	public ChangePasswordService changePasswordService() {
		return new ChangePasswordService();
	}

	@Bean
	public JoinService joinService() {
		return new JoinService();
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		DataSourceTransactionManager tm = new DataSourceTransactionManager();
		tm.setDataSource(dataSource());
		return tm;
	}

	@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:config-mybatis.xml"));
        //factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/**/*.xml"));
        factoryBean.setTypeAliasesPackage("mybatis.dao");
        return factoryBean.getObject();
    }
	
//	@Bean
//	public SqlSessionFactory sqlSessionFactory() throws Exception {
//		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
//		sqlSessionFactory.setDataSource(dataSource());
//		return (SqlSessionFactory) sqlSessionFactory.getObject();
//	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory());
	}


	@Bean
	public MyController myController() {
		return new MyController();
	}

	@Bean
	public LogController logController() {
		return new LogController();
	}
	
	@Bean
	public ArticleContentDao articleContentDao() {
		return new ArticleContentDao(dataSource());
	}
	
	@Bean
	public ArticleDao articleDao() {
		return new ArticleDao(dataSource());
	}
	
	@Bean
	public ListArticleService listArticleService() {
		return new ListArticleService();
	}
	@Bean
	public ModifyArticleService modifyArticleService() {
		return new ModifyArticleService();
	}
	@Bean
	public ReadArticleService readArticleService() {
		return new ReadArticleService();
	}
	@Bean
	public WriteArticleService writeArticleService() {
		return new WriteArticleService();
	}
	@Bean
	ArtController artController() {
		return new ArtController();
	}

}

 

package config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.jsp("/WEB-INF/view/", ".jsp");
	}
	

}

 

 

controller

package controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import article.model.Writer;
import article.service.ArticleContentNotFoundException;
import article.service.ArticleData;
import article.service.ArticleNotFoundException;
import article.service.ArticlePage;
import article.service.ListArticleService;
import article.service.ModifyArticleService;
import article.service.ModifyRequest;
import article.service.PermissionDeniedException;
import article.service.ReadArticleService;
import article.service.WriteArticleService;
import article.service.WriteRequest;
import auth.service.User;



@Controller
public class ArtController {
	@Autowired
	private ListArticleService listArticleService;
	
	@Autowired
	private ModifyArticleService modifyArticleService;
	
	@Autowired
	private ReadArticleService readArticleService;
	
	@Autowired
	private WriteArticleService writeArticleService;
	

	
	///article/write.do=article.command.WriteArticleHandler
	///article/list.do=article.command.ListArticleHandler
	///article/read.do=article.command.ReadArticleHandler
	///article/modify.do=article.command.ModifyArticleHandler
	
	@GetMapping("/article/list.do")
	public String listArticle(HttpServletRequest req) {
		
		String pageNoVal = req.getParameter("pageNo");
		int pageNo = 1;
		if (pageNoVal != null) {
			pageNo = Integer.parseInt(pageNoVal);
		}
		ArticlePage articlePage = listArticleService.getArticlePage(pageNo);
		req.setAttribute("articlePage", articlePage);
		return "listArticle";
		
		
	}
	@GetMapping("/article/read.do")
	public String readArticle(HttpServletRequest req, HttpServletResponse res) {
		
		String noVal = req.getParameter("no");
		int articleNum = Integer.parseInt(noVal);
		try {
			ArticleData articleData = readArticleService.getArticle(articleNum, true);
			req.setAttribute("articleData", articleData);
			return "readArticle";
		} catch (ArticleNotFoundException | ArticleContentNotFoundException e) {
			req.getServletContext().log("no article", e);
			try {
				res.sendError(HttpServletResponse.SC_NOT_FOUND);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return null;
		}
		
		
	}
	
	@GetMapping("/article/write.do")
	public String writeArticle1() {
		return "newArticleForm";
	}
	
	private WriteRequest createWriteRequest(User user, HttpServletRequest req) {
		return new WriteRequest(
				new Writer(user.getId(), user.getName()),
				req.getParameter("title"),
				req.getParameter("content"));
	}
	
	@PostMapping("/article/write.do")
	public String writeArticle2(HttpServletRequest req, HttpServletResponse res) {
		
		Map<String, Boolean> errors = new HashMap<>();
		req.setAttribute("errors", errors);

		User user = (User)req.getSession(false).getAttribute("authUser");
		WriteRequest writeReq = createWriteRequest(user, req);
		writeReq.validate(errors);
		
		if (!errors.isEmpty()) {
			return "newArticleForm";
		}
		
		int newArticleNo = writeArticleService.write(writeReq);
		req.setAttribute("newArticleNo", newArticleNo);
		
		return "newArticleSuccess";
		
		
	}
	
	@GetMapping("/article/delete.do")
	public String delete(){
		return "delete";
	}	
	
	private boolean canModify(User authUser, ArticleData articleData) {
		String writerId = articleData.getArticle().getWriter().getId();
		return authUser.getId().equals(writerId);
	}
	
	@GetMapping("/article/modify.do")
	public String modifyArticle1(HttpServletRequest req, HttpServletResponse res) {
		
		try {
			String noVal = req.getParameter("no");
			int no = Integer.parseInt(noVal);
			ArticleData articleData = readArticleService.getArticle(no, false);
			User authUser = (User) req.getSession().getAttribute("authUser");
			if (!canModify(authUser, articleData)) {
				res.sendError(HttpServletResponse.SC_FORBIDDEN);
				return null;
			}
			ModifyRequest modReq = new ModifyRequest(authUser.getId(), no,
					articleData.getArticle().getTitle(),
					articleData.getContent());

			req.setAttribute("modReq", modReq);
			return "modifyForm";
		} catch (ArticleNotFoundException | IOException e) {
			try {
				res.sendError(HttpServletResponse.SC_NOT_FOUND);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return null;
		}
		
		
	}
	
	@PostMapping("/article/modify.do")
	public String modifyArticle2(HttpServletRequest req, HttpServletResponse res) {
		
		User authUser = (User) req.getSession().getAttribute("authUser");
		String noVal = req.getParameter("no");
		int no = Integer.parseInt(noVal);

		ModifyRequest modReq = new ModifyRequest(authUser.getId(), no,
				req.getParameter("title"),
				req.getParameter("content"));
		req.setAttribute("modReq", modReq);

		Map<String, Boolean> errors = new HashMap<>();
		req.setAttribute("errors", errors);
		modReq.validate(errors);
		if (!errors.isEmpty()) {
			return "modifyForm";
		}
		try {
			modifyArticleService.modify(modReq);
			return "modifySuccess";
		} catch (ArticleNotFoundException e) {
			try {
				res.sendError(HttpServletResponse.SC_NOT_FOUND);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return null;
		} catch (PermissionDeniedException e) {
			try {
				res.sendError(HttpServletResponse.SC_FORBIDDEN);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return null;
		}
		
		
	}
	

	

	
	
}

 

 

 

 

 

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-08-17 63일차  (0) 2023.08.17
2023-08-16 62일차  (0) 2023.08.16
2023-08-10 60일차  (0) 2023.08.10
2023-08-09 59일차  (0) 2023.08.09
2023-08-08 58일차  (0) 2023.08.08

+ Recent posts