본문 바로가기
Spring

2024_08_12_월

by 알케니브 2024. 8. 12.

오늘의 코딩순서

(폴더: oBootMybatis01)

1. 회원 목록 (기본 CRUD)=> Validation 방식

1. writeFormEmp3 => Validation check 용도 기본틀

  • writeFormEmp3.jsp + EmpController.class + Emp.class(DTO) + Emp.xml

2. 페이징 작업 - 메인 페이지 + List

  • list.jsp
    + EmpController.class + EmpService.interface + EmpServiceImpl.class
    + EmpDao.interface+ EmpDaoImpl.class + Emp.xml

3. 이름 혹은 업무 조회

  • EmpController.class + EmpService.interface + EmpServiceImpl.class
    + EmpDao.interface+ EmpDaoImpl.class + Emp.xml

오늘의 코딩 포인트

1. writeFormEmp3 => Validation check 용도

  • writeFormEmp3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
	<!-- Validation check -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function chk() {
		if (!frm.empno.value) {
			alert("사번을 입력해주세요")
			frm.empno.focus();
			return false;
		} else location.href="confirm?empno="+frm.empno.value;
	}
</script>
</head>
<body>
<h2>직원정보 입력(Validation check 용도)</h2>
	<c:if test="${msg!=null}">${msg}</c:if>
		<form:form action="writeEmp3" method="post" name="frm" modelAttribute="emp">
			<table>
				<tr><th>사번</th><td><input type="number"	name="empno" required="required"
															maxlength="4"	value="${empno }">
									<input type="button" value="중복확인" onclick="chk()">
								</td>
				</tr>
				<tr><th>이름</th>
					<td><input type="text"		name="ename">
						<form:errors path="ename"/>
					</td>
				</tr>
				<tr><th>업무</th><td><input type="text"		name="job"			required="required"></td></tr>
				<tr><th>급여</th><td><input type="number"	name="sal"			required="required"></td></tr>
				<tr><th>입사일</th><td><input type="date"	name="hiredate"		required="required"></td></tr>
				<tr><th>보너스</th><td><input type="number"	name="comm"			required="required"></td></tr>
				<tr><th>관리자사번</th><td>
					<select name="mgr">
						<c:forEach var="emp" items="${empMngList}">
							<option value="${emp.empno}">${emp.ename}</option>
						</c:forEach>
					</select>			</td>
				</tr>
				
				<tr><th>부서코드</th><td>
					<select name="deptno">
						<c:forEach var="dept" items="${deptList}">
							<option value="${dept.deptno}">${dept.dname}</option>
						</c:forEach>
					</select>			</td>
				</tr>
				
				<tr><td colspan="2"><input type="submit" value="확인"></td>
				</tr>
						
			</table>
		</form:form>
</body>
</html>
  • EmpController.class
package com.oracle.oBootMybatis01.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;
import com.oracle.oBootMybatis01.service.EmpService;
import com.oracle.oBootMybatis01.service.Paging;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequiredArgsConstructor
@Slf4j
public class EmpController {
	
	private final EmpService es;

	// Validate 방법
	// writeFormEmp3와 연결
	@RequestMapping(value = "writeFormEmp3")
	public String writeFormEmp3(Model model) {
		System.out.println("empController writeFormEmp3 Start...");
		
		// 관리자사번만 Get
		List<Emp> empList = es.listManager();
		System.out.println("EmpController writeForm3 empList.size()->"+empList.size());
		
		model.addAttribute("empMngList",empList);	// emp Manager List
		// 부서(코드,부서명)
		List<Dept> deptList = es.deptSelect(); 
		model.addAttribute("deptList", deptList); // dept
		System.out.println("EmpController writeForm3 deptList.size->"+deptList.size());
		
		return "writeFormEmp3";
	}
	// Validation시 참조
	@PostMapping(value = "writeEmp3")
	public String writeEmp3(@ModelAttribute("emp") @Valid Emp emp
			// <form:form action="writeEmp3" modelAttribute="emp"> 와 이름 같게하기
							, BindingResult result
							, Model model) {
		System.out.println("EmpController writeEmp3 Start...");
		
		// Validation 오류시 Result
		if (result.hasErrors()) {
			System.out.println("EmpController writeEmp3 hasErrors...");
			model.addAttribute("msg", "BindingResult 입력 실패. 확인해 보세요.");
			return "forward:writeFormEmp3";
		}
		
		int insertResult = es.insertEmp(emp);
		
		if (insertResult > 0)
			return "redirect:listEmp";
			// insertResult 1일때 입력 성공
		else {
			model.addAttribute("msg", "입력 실패. 확인해 보세요.");
			
			return "forward:writeFormEmp3";
			// 입력 실패시 위의 writeFormEmp3로 돌아가되 msg의 값을 가져가므로,
			// writeFormEmp3의 <c:if test="${msg!=null}">${msg}</c:if> 값이 출력되어
			// 메시지가 나타남
		}
	}
	
}
  • Emp.class(DTO) 
package com.oracle.oBootMybatis01.model;

import jakarta.validation.constraints.NotEmpty;
import lombok.Data;

@Data
public class Emp {
	private int		empno;
	
	@NotEmpty(message = "이름은 필수입니다 흑유흑유")
	private String	ename;
	private String	job;
	private int		mgr;
	private String	hiredate;
	private int		sal;
	private int		comm;
	private int		deptno;
	
	// 조회용
	private String	search;
	private String	keyword;
	private String	pageNum;
	private int		start;
	private int		end;
	
	// Page 정보
	private String	currentPage;
	
	// 프로젝트시 DTO파일을 여러개 만드는 것보다,
	// 아래에 @Transient 어노테이션을 걸고 더 추가하는 것이 유지보수에 좋음
	
}
  • Emp.xml
    Tip)
    • Mapper(xml파일)에서는 주석표시나 부등호가 꺾쇠표시로 인식되기 때문에, 되도록 사용하지 않는 것이 좋음
      부등호를 사용해야 한다면, <![CDATA[]]>를 사용하여 안에 SQL문을 넣어 오라클에서 해결하도록 해야함
<?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="com.oracle.oBootMybatis01.EmpMapper">

	<select id="empTotal" resultType="int">
	
		SELECT Count(*) FROM emp
	 
	</select>
	
	<select id="tkEmpListAll" parameterType="Emp" resultType="Emp">
		<![CDATA[
		
		SELECT*
		FROM
		(
    		SELECT rownum rn, a.*
   			FROM
        		(
           			SELECT * FROM emp
            		ORDER BY empno) a
    	)
   		WHERE	rn >= #{start}
		AND 	rn <= #{end}
		]]>
	</select>

Validation을 활용한 오류 체크 방법


2. 페이징 작업 - 메인 페이지 + List 

  • list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>회원관리 </h1>

	<a href="writeFormEmp">writeFormEmp 입력</a><p>
	<a href="writeFormEmp3">writeFormEmp3 입력(Validation)</a>

<h3>사원수 : ${totalEmp }</h3>
	<p>uptCnt	수정시 전달 Message : ${uptCnt} <p>
	<p>kk3		수정시 전달 Message : ${kk3}<p>
	
	<form action="listSearch3">
		<select name="search">
				<option value="s_job">업무조회</option>
				<option value="s_ename">이름조회</option>
		</select>
		
		<input type="text" name="keyword" placeholder="keyword를 입력하세요">
		<button type="submit">keyword 검색</button><p>
	</form>
	

	<c:set var="num" value="${page.total-page.start+1 }"></c:set>		
	
	<table>
		<tr>
			<th>번호</th> <th>사번</th> <th>이름</th> 
			<th>업무</th> <th>급여</th>
		</tr>
		<c:forEach var="emp" items="${listEmp }">
			<tr>
				<td>${num }</td><td>${emp.empno }</td>
				<td><a href="detailEmp?empno=${emp.empno }">${emp.ename }</a></td>
				<td>${emp.job }</td><td>${emp.sal }</td>
			</tr>
			<c:set var="num" value="${num - 1 }"></c:set>
		</c:forEach>	
	</table>
	
	<c:if test="${page.startPage > page.pageBlock }">
		<a href="listEmp?currentPage=${page.startPage-page.pageBlock }">[이전]</a>	
	</c:if>
	<c:forEach var="i" begin="${page.startPage }" end="${page.endPage }">
		<a href="listEmp?currentPage=${i}">[${i}]</a>
	</c:forEach>
	
	<c:if test="${page.endPage < page.totalPage }">
		<a href="listEmp?currentPage=${page.startPage+page.pageBlock }">[다음]</a>
	</c:if>
</body>
</html>
  • EmpController.class
package com.oracle.oBootMybatis01.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;
import com.oracle.oBootMybatis01.service.EmpService;
import com.oracle.oBootMybatis01.service.Paging;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequiredArgsConstructor
@Slf4j
public class EmpController {
	
	private final EmpService es;
	
	// 1. 메인 페이지( 화면 + list 조회)
	@RequestMapping(value = "listSearch3")
	public String listSearch3(Emp emp, Model model) {
		System.out.println("EmpController listEmp Start...");
		System.out.println("EmpController listSearch3 emp->"+emp);
		
		// Emp 전체 Count
		int totalEmp = es.condEmpTotal(emp);
		System.out.println("EmpController listSearch3 totalEmp->"+totalEmp);
		
		// Paging 작업
		Paging page = new Paging(totalEmp, emp.getCurrentPage());
		
		// Parameter emp ==> Page만 추가 Setting
		emp.setStart(page.getStart());	// 시작시 1
		emp.setEnd(page.getEnd());		// 시작시 10
		System.out.println("EmpController listSearch3 page->"+page);

		return "list";
	}
	
}
  • EmpService.interface
package com.oracle.oBootMybatis01.service;

import java.util.List;

import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;

public interface EmpService {
	int			totalEmp();
	List<Emp> 	listEmp(Emp emp);
	
	// (0809)현장HW 2-2
	Emp 		detailEmp(int empno);
	// (0809)현장HW 3-2
	int 		updateEmp(Emp emp);
	// (0812)현장 1-2
	List<Emp> 	listManager();
	
	List<Dept> deptSelect();
	// (0812)현장 3-1
	int 		insertEmp(Emp emp);
	// (0812)현장 4-1
	int 		deleteEmp(int empno);
	
	
	// Validate 방법
	int 		condEmpTotal(Emp emp);
}
  • EmpServiceImpl.class
package com.oracle.oBootMybatis01.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.oracle.oBootMybatis01.dao.DeptDao;
import com.oracle.oBootMybatis01.dao.EmpDao;
import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class EmpServiceImpl implements EmpService {
	
	private final EmpDao ed;
	private final DeptDao dd;
		// 서로 다른 Interface(DAO)를 받은 것이기 때문에 두 개 이상 가능 

	// Validate 방법
	@Override
	public int condEmpTotal(Emp emp) {
		System.out.println("EmpServiceImpl total Start...");
		
		int totEmpCnt = ed.condEmpTotal(emp);
		System.out.println("EmpServiceImpl totalEmp totEmpCnt->"+totEmpCnt);
		
		return totEmpCnt;
	}

}
  • EmpDao.interface
package com.oracle.oBootMybatis01.dao;

import java.util.List;

import com.oracle.oBootMybatis01.model.Emp;

public interface EmpDao {

	int			totalEmp();

	List<Emp> 	listEmp(Emp emp);
	
	// (0809)현장 HW 2-4
	Emp 		detailEmp(int empno);
	// (0809)현장 HW 3-4
	int 		updateEmp(Emp emp);
	// (0812)현장 1-4
	List<Emp> 	listManager();
	
	// (0812)현장 3-3
	int 		insertEmp(Emp emp);

	// (0812)현장 4-3
	int 		deleteEmp(int empno);

	// Validate 방법
	int 		condEmpTotal(Emp emp);
	
}
  • EmpDaoImpl.class
package com.oracle.oBootMybatis01.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.oracle.oBootMybatis01.model.Emp;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class EmpDaoImpl implements EmpDao {
	// Mybatis DB 연동 
	private final SqlSession session;

	// Validate 방법
	@Override
	public int condEmpTotal(Emp emp) {
		int totEmpCount = 0;
		System.out.println("EmpDaoImpl total Start...");
		
		try {
			totEmpCount = session.selectOne("condEmpTotal", emp);
			System.out.println("EmpDaoImpl totalEmp totEmpCount->"+totEmpCount);
		
		} catch (Exception e) {
			System.out.println("EmpDaoImpl totalEmp Exception->"+e.getMessage());
		}
		
		return totEmpCount;
	}
	
}
  • Emp.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="com.oracle.oBootMybatis01.EmpMapper">
	
	<select id="condEmpTotal" parameterType="Emp" resultType="int">
		SELECT Count(*)	FROM emp
		<choose>
			<when test="search == 's_job'">
				WHERE job like '%' || #{keyword} || '%'
			</when>
			<when test="search == 's_ename'">
				WHERE ename like '%' || #{keyword} || '%'
			</when>
			<otherwise>
				WHERE job like '%'	
			</otherwise>
		</choose>
	
	</select>	

</mapper>

 

 


3. 이름 혹은 업무 조회

  • EmpController.class
package com.oracle.oBootMybatis01.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;
import com.oracle.oBootMybatis01.service.EmpService;
import com.oracle.oBootMybatis01.service.Paging;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequiredArgsConstructor
@Slf4j
public class EmpController {
	
	private final EmpService es;
	
	// 1. 메인 페이지( 화면 + list 조회)
	@RequestMapping(value = "listSearch3")
	public String listSearch3(Emp emp, Model model) {
		System.out.println("EmpController listEmp Start...");
		System.out.println("EmpController listSearch3 emp->"+emp);
		
		// Emp 전체 Count
		int totalEmp = es.condEmpTotal(emp);
		System.out.println("EmpController listSearch3 totalEmp->"+totalEmp);
		
		// Paging 작업
		Paging page = new Paging(totalEmp, emp.getCurrentPage());
		
		// Parameter emp ==> Page만 추가 Setting
		emp.setStart(page.getStart());	// 시작시 1
		emp.setEnd(page.getEnd());		// 시작시 10
		System.out.println("EmpController listSearch3 page->"+page);
		
		// 현장 HW
		// 2. 이름 혹은 업무 조회
		List<Emp> listSearchEmp = es.listSearchEmp(emp);
		// 1. DAO  ed.empSearchList3(emp);
        // 2. Mapper selectList("tkEmpSearchList3", emp);
		
		System.out.println("EmpController listSearch3 listSearchEmp.size()->"+listSearchEmp.size());
		
		model.addAttribute("totalEmp", totalEmp);
		model.addAttribute("listEmp" , listSearchEmp);
		model.addAttribute("page"    , page);
		
		return "list";
	}
	
}
  • EmpService.interface
package com.oracle.oBootMybatis01.service;

import java.util.List;

import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;

public interface EmpService {
	int			totalEmp();
	List<Emp> 	listEmp(Emp emp);
	
	// (0809)현장HW 2-2
	Emp 		detailEmp(int empno);
	// (0809)현장HW 3-2
	int 		updateEmp(Emp emp);
	// (0812)현장 1-2
	List<Emp> 	listManager();
	
	List<Dept> deptSelect();
	// (0812)현장 3-1
	int 		insertEmp(Emp emp);
	// (0812)현장 4-1
	int 		deleteEmp(int empno);
	
	
	// Validate 방법
	int 		condEmpTotal(Emp emp);
	
	// 현장 HW
	List<Emp> listSearchEmp(Emp emp);
}
  • EmpServiceImpl.class
package com.oracle.oBootMybatis01.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.oracle.oBootMybatis01.dao.DeptDao;
import com.oracle.oBootMybatis01.dao.EmpDao;
import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.Emp;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class EmpServiceImpl implements EmpService {
	
	private final EmpDao ed;
	private final DeptDao dd;
		// 서로 다른 Interface(DAO)를 받은 것이기 때문에 두 개 이상 가능 

	@Override
	public List<Emp> listSearchEmp(Emp emp) {
		List<Emp> empSearchList = null;
		System.out.println("EmpServiceImpl listEmp Start...");
		
		empSearchList = ed.empSearchList3(emp);
		System.out.println("EmpServiceImpl listSearchEmp empSearchList->"+empSearchList.size());
		
		return empSearchList;
	}

}
  • EmpDao.interface
package com.oracle.oBootMybatis01.dao;

import java.util.List;

import com.oracle.oBootMybatis01.model.Emp;

public interface EmpDao {

	int			totalEmp();

	List<Emp> 	listEmp(Emp emp);
	
	// (0809)현장 HW 2-4
	Emp 		detailEmp(int empno);
	// (0809)현장 HW 3-4
	int 		updateEmp(Emp emp);
	// (0812)현장 1-4
	List<Emp> 	listManager();
	
	// (0812)현장 3-3
	int 		insertEmp(Emp emp);

	// (0812)현장 4-3
	int 		deleteEmp(int empno);

	// Validate 방법
	int 		condEmpTotal(Emp emp);

	// 현장 HW
	List<Emp> empSearchList3(Emp emp);
	
}
  • EmpDaoImpl.class
package com.oracle.oBootMybatis01.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.oracle.oBootMybatis01.model.Emp;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class EmpDaoImpl implements EmpDao {
	// Mybatis DB 연동 
	private final SqlSession session;

	@Override
	public List<Emp> empSearchList3(Emp emp) {
		List<Emp> empSearchList3 = null;
		System.out.println("EmpDaoImpl empSearchList3 Start...");
		
		try {
			empSearchList3 = session.selectList("tkEmpSearchList3",emp);
			System.out.println("EmpDaoImpl listEmp empSearchList3->"+empSearchList3);
			
		} catch (Exception e) {
			System.out.println("EmpDaoImpl listEmp Exception->"+e.getMessage());
		}
		
		return empSearchList3;
	}
	
}
  • Emp.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="com.oracle.oBootMybatis01.EmpMapper">
	
	<select id="tkEmpSearchList3" parameterType="Emp" resultType="Emp">
		SELECT*
		FROM
		(
    		SELECT rownum rn, a.*
   			FROM
        			(
           			SELECT * 
           			FROM emp
            		<choose>
            			<when test="search == 's_job'">
            				WHERE job like '%' || #{keyword} || '%'
            			</when>
            			<when test="search == 's_ename'">
            				WHERE ename like '%' || #{keyword} || '%'
            			</when>
            			<otherwise>
            				Where job like '%'
            			</otherwise>
            		</choose>
					ORDER BY empno
					) a
    	)
   		WHERE rn BETWEEN #{start} and #{end}
	</select>

</mapper>

질문목록

 


수업교재

 

 


오늘의 숙제

'Spring' 카테고리의 다른 글

2024_08_14_수  (0) 2024.08.14
2024_08_13_화  (0) 2024.08.13
2024_08_08_목~08_12_월  (0) 2024.08.08
2024_08_07_수~08_08_목  (0) 2024.08.07
2024_08_06_화~08_07_수  (0) 2024.08.06