수업/몽고디비

몽고디비 - 성적 등록하기

가평잣막걸리 2024. 7. 10. 11:11

 

 

ScoreVO 

 

 

controller

몽고디비 score collection에 넣어보기 시작

 

 

뷰단 만들어준다.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ 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>spring</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
* { padding: 0; margin: 0; }
*, *::after, *::before { box-sizing: border-box; }

body {
	font-family:"Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif;
	font-size: 14px;
	color: #222;
}

a { color: #222; text-decoration: none; cursor: pointer; }
a:active, a:hover { color: #f28011; text-decoration: underline; }

/* form-control */
.btn {
	color: #333;
	border: 1px solid #999;
	background-color: #fff;
	padding: 5px 10px;
	border-radius: 4px;
	font-weight: 500;
	cursor:pointer;
	font-size: 14px;
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.btn:active, .btn:focus, .btn:hover {
	background-color: #f8f9fa;
	color:#333;
}
.btn[disabled], fieldset[disabled] .btn {
	pointer-events: none;
	cursor: default;
	opacity: .65;
}

.form-control {
	border: 1px solid #999; border-radius: 4px; background-color: #fff;
	padding: 5px 5px; 
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.form-control[readonly] { background-color:#f8f9fa; }

textarea.form-control { height: 170px; resize : none; }

.form-select {
	border: 1px solid #999; border-radius: 4px; background-color: #fff;
	padding: 4px 5px; 
	font-family: "맑은 고딕", 나눔고딕, 돋움, sans-serif;
	vertical-align: baseline;
}
.form-select[readonly] { background-color:#f8f9fa; }

textarea:focus, input:focus { outline: none; }
input[type=checkbox], input[type=radio] { vertical-align: middle; }

/* table */
.table { width: 100%; border-spacing: 0; border-collapse: collapse; }
.table th, .table td { padding-top: 10px; padding-bottom: 10px; }

.table-border thead > tr { border-top: 2px solid #212529; border-bottom: 1px solid #ced4da; }
.table-border tbody > tr { border-bottom: 1px solid #ced4da; }
.table-border tfoot > tr { border-bottom: 1px solid #ced4da; }
.td-border td { border: 1px solid #ced4da; }

/* container */
.container { width: 500px; margin: 30px auto; }

.title { width:100%; font-size: 16px; font-weight: bold; padding: 13px 0; }

.table-form td { padding: 7px 0; }
.table-form tr:first-child { border-top: 2px solid #212529; }
.table-form tr > td:first-child { text-align: center; background: #f8f9fa; width: 100px; }
.table-form tr > td:nth-child(2) { padding-left: 10px; }
.table-form input[type=text], .table-form input[type=date] { width: 96%; }

</style>

<script type="text/javascript">


/*
	yyyy-mm-dd형식에 맞춰서 유효한 날짜인지 체크해주는 코드입니다.
	윤달까지 고려하여 유효한 날짜인지 체크해주는 코드입니다.
*/
function isValidDateFormat(value) {
	var result = true;
	try {
	    var date = value.split("-");
	    var y = parseInt(date[0], 10),
	        m = parseInt(date[1], 10),
	        d = parseInt(date[2], 10);
	    
	    var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	    result = dateRegex.test(d+'-'+m+'-'+y);
	} catch (err) {
		result = false;
	}    
    return result;	
}

function isValidScoreFormat(data) {
	let regexp = /^(\d+)$/;
    if(! regexp.test(data)) {
        return false;
    }
    let s = parseInt(data);
	return s>=0 && s<=100 ? true : false;
}

function sendOk() {
	const f = document.scoreForm;
	
	if(f.hakbeon.value.trim() == "") {
        alert("필수 입력 사항 입니다. !!!");
        f.hakbeon.focus();
        return;
	}

	if(f.dept.value.trim() == "") {
        alert("필수 입력 사항 입니다. !!!");
        f.dept.focus();
        return;
	}
	
	if(f.name.value.trim() == "") {
        alert("필수 입력 사항 입니다. !!!");
        f.name.focus();
        return;
	}
	
    if(! isValidDateFormat(f.birth.value)) {
        alert("날짜 형식이 유효하지 않습니다. ");
        f.birth.focus();
        return;
	}
	
    if(! isValidScoreFormat(f.kor.value)) {
		alert("점수는 0~100 사이만 가능합니다. ");
		f.kor.focus();
		return;
    }
    
    if(! isValidScoreFormat(f.eng.value)) {
        alert("점수는 0~100 사이만 가능합니다. ");
        f.eng.focus();
        return;
	}
    
    if(! isValidScoreFormat(f.mat.value)) {
        alert("점수는 0~100 사이만 가능합니다. ");
        f.mat.focus();
        return;
	}
	
    f.action="${pageContext.request.contextPath}/mscore/${requestScope.mode}";
	f.submit();
}
</script>
</head>
<body>

<div class="container">
	<div class="title">
	    <h3><span>|</span> 성적처리</h3>
	</div>

	<form name="scoreForm" method="post">
		<table class="table table-border table-form">
		<tr>
			<td>학 번</td>
			<td>
				<input type="text" name="hakbeon" class="form-control" maxlength="10" value="${requestScope.dto.hakbeon}"
						${requestScope.mode=="update"?"readonly='readonly'":""}>
			</td>
		</tr>

		<tr>
			<td>학과</td>
			<td>
				<input type="text" name="dept" class="form-control" maxlength="10" value="${requestScope.dto.dept}">
			</td>
		</tr>
		
		<tr>
			<td>이 름</td>
			<td>
				<input type="text" name="name" class="form-control" maxlength="10" value="${requestScope.dto.name}">
			</td>
		</tr>
		
		<tr>
			<td>생년월일</td>
			<td>
				<input type="date" name="birth" class="form-control" maxlength="10" value="${requestScope.dto.birth}">
			</td>
		</tr>
		
		<tr>
			<td>국 어</td>
			<td>
				<input type="text" name="kor" class="form-control" maxlength="3" value="${requestScope.dto.kor}">
			</td>
		</tr>
		
		<tr>
			<td>영 어</td>
			<td>
				<input type="text" name="eng" class="form-control" maxlength="3" value="${requestScope.dto.eng}">
			</td>
		</tr>
		
		<tr>
			<td>수 학</td>
			<td>
				<input type="text" name="mat" class="form-control" maxlength="3" value="${requestScope.dto.mat}">
			</td>
		</tr>
		</table>
		
		<table class="table">
			<tr>
				<td align="center" colspan="2">
					<button type="button" class="btn" onclick="sendOk();"> ${requestScope.mode=="update"?"수정완료":"등록완료"} </button> 
					<button type="reset"  class="btn"> 다시입력 </button>
					<button type="button" class="btn"
						onclick="javascript:location.href='${pageContext.request.contextPath}/mscore/list';"> ${requestScope.mode=="update"?"수정취소":"등록취소"} </button> 
				</td>
			</tr>
		</table>
	</form>
	
</div>

</body>
</html>

 

뷰단에서 넘어온 VO를 갖고 디비에 insert할거임

controller

 

service

폼태그에서 에서 국영수 점수를 가져와서 백단에서 총합과 평균을 계산한 뒤 set해줌

=> 밑에 페이지 결과물 보면 총합,평균이 보인다.

 

 

ScoreMongoOperations

	public void insertScore(Score dto) throws Exception{
		
		try {
			// >>> 데이터 추가 <<<
			//mongo.save(dto, "score"); // 없으면 추가, 있으면 수정.  이것을 실행되면 mongodb 의 데이터베이스 mydb 에 score 라는 컬렉션이 없다라도 자동적으로 먼저  score 컬렉션을 생성해준 다음에 도큐먼트를 추가시켜준다.
			mongo.save(dto); // 없으면 추가, 있으면 수정.  com.spring.app.mongodb.Score 클래스 생성시 @Document(collection = "score") 어노테이션을 설정했으므로 두번째 파라미터로 "score" 은 생략가능하다.
		} catch(Exception e) {
			e.printStackTrace();
			
			throw e;
		}
	}

몽고디비에 넣어준다