Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

게으른 완벽주의자의 개발자 도전기

[ajax] 학생정보시스템 점수상세페이지, 점수등록 본문

Spring Boot

[ajax] 학생정보시스템 점수상세페이지, 점수등록

머리방울 2022. 9. 12. 21:56

1. mapper

1. 이름 클릭하여 점수목록 보기
<select id="selectScore" resultMap="score">
SELECT ST.STU_NUM
        , STU_NAME
        , CLASS_NAME
        , NVL(KOR_SCORE, 0) AS KOR_SCORE
		, NVL(ENG_SCORE, 0) AS ENG_SCORE
		, NVL(MATH_SCORE, 0) AS MATH_SCORE
	FROM SCORE_INFO SC, CLASS_INFO CL, STUDENT_INFO ST
    WHERE ST.CLASS_CODE = CL.CLASS_CODE
    AND ST.STU_NUM = SC.STU_NUM(+)
    AND ST.STU_NUM = #{stuNum}
</select>

2. 점수등록
<insert id="insertScore">
	MERGE INTO SCORE_INFO
	USING DUAL
	ON (STU_NUM = #{stuNum}) <-UPDATE/INSERT 결정 조건 넣기
	WHEN MATCHED THEN
		UPDATE
		SET
		KOR_SCORE = #{korScore}
		, ENG_SCORE=#{engScore}
		, MATH_SCORE=#{mathScore}
		WHERE STU_NUM = #{stuNum}
	
	WHEN NOT MATCHED THEN
		INSERT(
			SCORE_NUM
			, STU_NUM
			, KOR_SCORE
			, MATH_SCORE
			, ENG_SCORE
		)VALUES(
			(SELECT NVL(MAX(SCORE_NUM), 0) +1 FROM SCORE_INFO)
			, #{stuNum}
			, #{korScore}
			, #{mathScore}
			, #{engScore}
			
		)
</insert>


<resultMap type="kh.study.ajax.vo.ScoreVO" id="score">
<id column="SCORE_NUM" property="scoreNum"/>
<result column="KOR_SCORE" property="korScore"/>
<result column="ENG_SCORE" property="engScore"/>
<result column="MATH_SCORE" property="mathScore"/>
<result column="STU_NUM" property="stuNum"/>

<result column="STU_NAME"	property="stuName"/>
<result column="CLASS_NAME" property="className"/>
</resultMap>

 

2. 인터페이스 , serviceImpl

점수목록(학생이름 클릭 시)
ScoreVO selectScore(int stuNum);
	
점수등록
int insertScore(ScoreVO score);


점수목록(학생이름 클릭 시)
@Override
public ScoreVO selectScore(int stuNum) {
		
	return sqlSession.selectOne("stuMapper.selectScore", stuNum);
}

점수등록
@Override
public int insertScore(ScoreVO score) {
	return sqlSession.insert("stuMapper.insertScore", score);
}

 

3. controller

점수목록 상세조회(학생이름 클릭 시)
@ResponseBody
@PostMapping("/scoreList")
public ScoreVO selectScore(int stuNum){
   return stuService.selectScore(stuNum);	
}

점수등록(merge into)
@ResponseBody
@PostMapping("/insertScore")
public void insertScore(ScoreVO score) {
   stuService.insertScore(score);
}

 

4. html

<body>

	<table class="layout">
		<colgroup>
			<col width="50%">
			<col width="50%">
		</colgroup>
		<tr>
			<td>
				<div style="margin-bottom: 30px;">
					<select name="classCode" onchange="changeClass();">
						<option selected value="0">전체</option>
						<option th:each="classInfo:${classInfo}"
							th:text="${classInfo.className}"
							th:value="${classInfo.classCode}"></option>
					</select>
				</div>
				<div>
					<table class="stu">
						<thead>
							<tr>
								<td>학번</td>
								<td>이름</td>
								<td>나이</td>
								<td>학급명</td>
								<td></td>
							</tr>
						</thead>
						<tbody>
							<tr th:each="stu : ${stuInfo}">
								<td th:text="${stu.stuNum}">
								</td>
								
								<td><span th:text="${stu.stuName}"
									th:onclick="showDetail(this.getAttribute('stuNum'));"
									th:stuNum="${stu.stuNum}"></span></td>
								<td th:text="${stu.stuAge}"></td>
								<td th:text="${stu.className}"></td>
								<td><input type="button" value="삭제" 
								th:onclick="deleteStu(this.getAttribute('stuNum'), this);" 
								th:stuNum="${stu.stuNum}"></td>
							</tr>
						</tbody>
					</table>
				</div>
			</td>
			<td id="detailTd">
			</td>
		</tr>
	</table>

	<script src="https://code.jquery.com/jquery-latest.min.js"></script> <- jquery 실행
<script type="text/javascript" th:src="@{/stu_manage.js}"></script> <- static폴더 기준 
</body>

 

 

 

this 이해하기


<input id="aaaaa" type="text" onclick="aaa(this);">
<span id="bbbb" onclick="aaa(this);">span태그</span>
<div id="ccc" onclick="aaa(this);"></div>

tag라는 매개변수가 위에 태그들의 매개변수(this) 가져오는 것
<script type="text/javascript">
function aaa(tag){ 
console.log(tag.id);
console.log(tag.name);
console.log(tag.onclick);
}

input 태그 그자체 불러오기
const tag =  document.querySelector('input');
alert(tag.id); //aaaaa
alert(tag.type); //text
alert(tag.onclick) //aaa(this)



.innerText / .innerHTML 의미 
const d =  document.querySelector('div');
alert(d.id); //ccc
alert(d.innerText); //ccc
d.innerText = '<span>자바</span>'; span태그 사이에 글자를 입력
d.innerHTML = '<span>자바</span>'; span태그 사이에 html형식의 글자를 입력하는 것




</script>

 

 

5. js쿼리

학생이름 클릭 시 점수 정보
function showDetail(stuNum) {
	1). ajax 시작
	$.ajax({

		url: '/stu/scoreList', <- 요청경로
		type: 'post',
		data: { 'stuNum': stuNum }, <- 필요한 데이터

		success: function(result) {
			let str = '';
			str += '<table class="detailStu">';
			str += '<tr>                 ';
			str += '	<td>학생번호</td>';
			str += '	<td>학생이름</td>';
			str += '	<td>소속학급</td>';
			str += '</tr>                ';
			str += '<tr>                 ';
			str += `<td id="stuNumTd">${result.stuNum}</td>`;
			str += `<td>${result.stuName}</td>`;
			str += `<td>${result.className}</td>`;
			str += '</tr>                ';
			str += '<tr>                 ';
			str += '	<td>국어점수</td>';
			str += '	<td>영어점수</td>';
			str += '	<td>수학점수</td>';
			str += '</tr>                ';
			str += `<tr id="scoreTr">`;
			str += `<td>${result.korScore}</td>`;
			str += `<td>${result.engScore}</td>`;
			str += `<td>${result.mathScore}</td>`;
			str += '</tr>                ';
			str += '</table>                 ';
			str += '<br>'
			str += `<input type="button" id="setScoreBtn" value="점수등록" onclick= "setScore();">`

			const detailTd = document.querySelector('#detailTd');
			★td 안 내용 지우기(이름 누르고 다른 이름 눌렀을 때 지워지도록) 
			detailTd.innerHTML = '';	공백으로 만들기
			detailTd.insertAdjacentHTML('beforeend', str);	데이터 넣기

		},

		error: function() {
			alert('실패');
		}
	});
}


버튼 클릭 시 점수등록
function setScore() {
	const btn = document.querySelector('#setScoreBtn');
	
	버튼이 점수등록일 때
	if (btn.value == '점수등록') {
		점수칸 내용 지우고 input태그 넣을 것
		★selector쓰면 하나만 가져옴(selectAll tr의 자식태그 총3개 한 번에 가져옴)
		const scoreTds = document.querySelectorAll('#scoreTr > td');

		for (const scoreTd of scoreTds) {
			const score = scoreTd.innerText;
			기존 자료는 공백으로
			scoreTd.innerText = '';

			어디에 무엇을 넣을것인지? (기존 점수도 추가되어야 하니 value로), 백틱)
			const str = `<input class="scoreInput" type="text" style ="width: 90%;" value ="${score}">`;

			td 시작할 때(afterbegin) 또는 td끝나기 전(beforeEnd)
			scoreTd.insertAdjacentHTML('beforeend', str);
		}
		
        점수등록 -> 확인하기로 바꾸기
		btn.value = '확인';

	}
	
	버튼이 확인일 때
	else {
		국영수 input태그
		const scoreInputs = document.querySelectorAll('.scoreInput');
		const stuNum = document.querySelector('#stuNumTd').innerText;
		
		$.ajax({
			url: '/stu/insertScore', <-요청경로
			type: 'post',
			data: {'korScore' : scoreInputs[0].value
				, 'engScore' : scoreInputs[1].value 
				, 'mathScore' : scoreInputs[2].value
				, 'stuNum' : stuNum }, 배열처럼 순서대로 값 가져오기
			
			success: function(result) {
			
			},
		
			error: function() {
				alert('실패');
			}
		});
	
	}
	
}