TIL/academy

국비 TIL(Today I Learned) 20220804 스프링 게시판 글추가, 수정, 삭제

토희 2022. 8. 4. 17:30
728x90

* 복습

- select에서 resultType 필수적으로 넣어줘야함

- 쿼리 가져와서 붙일때 ;(세미콜론) 빼주기

- selectOne은여러줄 들어오면 터짐 ( 리스트 상세보기 들어갈때 selectOne으로 받음)

 

 

 

* 어제 실습

어제 매니저 리스트 가져오는 실습에서 강사님이랑 다른점!

나는 Test_SQL.XML에서 매니저리스트쪽에 parameterType에 hashmap이라고 적었는데,

 

 

TestDao.java에서 getManagerList에서 받는게 없으니 parameterType줄 필요가 없었음

parameterType이 dao받는값!, getManager는 params 받는게 있으니 parameterType적어줬구!

 

 

원래 빨간색 테투리부분이 MVC라고 하면, Controller영역을 좀더 세분화한게 Spring MVC(노란색박스)! 

 

 

주소창에 managerDetail로 주소를 바로  치면, 목록 상세보기 오류발생

그래서 if문으로 걸려줘야함

no값이 안넘어오면 목록으로 돌아가게 해주는데 redirect 사용

redirect가 get방식으로 되는 예

 

 

 

글 목록에서 글쓰기 버튼 만들어서, 페이지 만들기

 

 

 

SELL에 시퀀스 추가

 

 

처음에는 주소 다르게했다가 

 

 

통일해줌

 

 

커밋이나 롤백 해주기!

트랜잭션이 물려있어서 스프링에서 오류날수도 있데

 

 

 

오늘은 글추가, 목록, 삭제를 배움

어제의 SELL 테이블은 강사님이랑 같이하고, 실습으로 MANAGER 하고

 

TestController.java

package com.spring.sample.web.test.controller;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.spring.sample.web.test.service.ITestService;

@Controller
public class TestController {
	// 3.
	@Autowired
	public ITestService iTestService;

	/*
	 * Database나 파일 같이 외부에 접근하는 경우 외적 요인으로 문제가 발샐할 수 있음으로 예외처리가 반드시 필요하다.
	 */

	// 글 목록
	@RequestMapping(value = "/sellList")
	public ModelAndView sellList(ModelAndView mav) throws Throwable {
		// 데이터 취득
		List<HashMap<String, String>> list = iTestService.getSellList();

		mav.addObject("list", list);
		mav.setViewName("test/sellList");

		return mav;
	}

	// 글 상세보기
	@RequestMapping(value = "/sellDetail")
	// 페이지 이동할때 값이 하나가 넘어가는 경우가 거의 없음,
	// params를 다른이름 줘도됨, a이든 뭐든 상관없음, 여기서만, 나는 HashMap만 받으면 된다
	public ModelAndView sellDetail(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		// no가 값이 안 넘어오거나 no자체가 안넘어온 경우
		if (params.get("no") == null || params.get("no") == "") {
			// setViewName에서 redirect : 해당 주소로 이동한다.
			// 단, GET방식밖에 안됨
			// 사용시 고민해야부분 중 하나는 단순이동할때는 redirect, 나머지는 문제가 있을수있다. 값이 주소창에 나옴!
			// mav.addObject("test", "abc"); // get방식으로 쓰이는 예
			mav.setViewName("redirect:sellList");

		} else {
			HashMap<String, String> data = iTestService.getSell(params);

			mav.addObject("data", data);
			mav.setViewName("test/sellDetail");
		}

		return mav;
	}

	// 글 추가
	@RequestMapping(value = "/sellInsert")
	public ModelAndView sellInsert(ModelAndView mav) {
		// DB에 붙을게 없으니, 굳이 예외처리 할 필요 없음
		mav.setViewName("test/sellInsert");
		return mav;

	}

	// 글 등록
	@RequestMapping(value = "/sellRes")
	public ModelAndView sellInsertRes(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		try {
			int cnt = 0; // insert, update, delete 다 쓸거기 때문에 처음에 0줌

			switch (params.get("gbn")) {
			case "i":
				cnt = iTestService.insertSell(params);
				break;
			case "u":
				cnt = iTestService.updateSell(params);
				break;
			case "d":
				cnt = iTestService.deleteSell(params);
				break;
			}

			if (cnt > 0) { // 1건 이상 등록된 경우
				mav.addObject("res", "success");
			} else { // 등록 안된 경우
				mav.addObject("res", "failded");
			}
		} catch (Exception e) { // 예외 발생시
			e.printStackTrace();
			mav.addObject("res", "error");
		}
		mav.setViewName("test/sellRes");
		return mav;
	}

	// 글 수정페이지
	@RequestMapping(value = "/sellUpdate")
	public ModelAndView sellUpdate(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {
		// 기존데이터 조회해와야함
		HashMap<String, String> data = iTestService.getSell(params);
		mav.addObject("data", data);

		mav.setViewName("test/sellUpdate");

		return mav;

	}

	// 실습
	@RequestMapping(value = "/managerList")
	public ModelAndView managerList(ModelAndView mav) throws Throwable {
		// 데이터 취득
		List<HashMap<String, String>> list = iTestService.getManagerList();

		mav.addObject("list", list);
		mav.setViewName("test/managerList");

		return mav;
	}

	@RequestMapping(value = "/managerDetail")
	public ModelAndView managerDetail(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		if (params.get("no") == null || params.get("no") == "") {
			mav.setViewName("redirect:managerList");

		} else {
			HashMap<String, String> data = iTestService.getManager(params);

			mav.addObject("data", data);
			mav.setViewName("test/managerDetail");
		}

		return mav;
	}

	@RequestMapping(value = "/managerInsert")
	public ModelAndView managerInsert(ModelAndView mav) {
		mav.setViewName("test/managerInsert");
		return mav;

	}

	@RequestMapping(value = "/managerRes")
	public ModelAndView managerInsertRes(@RequestParam HashMap<String, String> params, ModelAndView mav)
			throws Throwable {

		try {
			int cnt = 0; // insert, update, delete 다 쓸거기 때문에 처음에 0줌

			switch (params.get("gbn")) {
			case "i":
				cnt = iTestService.insertManager(params);
				break;
			case "u":
				cnt = iTestService.updateManager(params);
				break;
			case "d":
				cnt = iTestService.deleteManager(params);
				break;
			}

			if (cnt > 0) { // 1건 이상 등록된 경우
				mav.addObject("res", "success");
			} else { // 등록 안된 경우
				mav.addObject("res", "failded");
			}
		} catch (Exception e) { // 예외 발생시
			e.printStackTrace();
			mav.addObject("res", "error");
		}
		mav.setViewName("test/managerRes");
		return mav;
	}

	// 글 수정페이지
	@RequestMapping(value = "/managerUpdate")
	public ModelAndView managerUpdate(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {
		// 기존데이터 조회해와야함
		HashMap<String, String> data = iTestService.getManager(params);
		mav.addObject("data", data);

		mav.setViewName("test/managerUpdate");

		return mav;

	}
}

 

ITestService.java

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

public interface ITestService {

	public List<HashMap<String, String>> getSellList() throws Throwable;

	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable;

	public int insertSell(HashMap<String, String> params) throws Throwable;

	public int deleteSell(HashMap<String, String> params) throws Throwable;

	public int updateSell(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getManagerList() throws Throwable;

	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable;

	public int insertManager(HashMap<String, String> params) throws Throwable;

	public int updateManager(HashMap<String, String> params) throws Throwable;

	public int deleteManager(HashMap<String, String> params) throws Throwable;

}

 

TestService.java

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.sample.web.test.dao.ITestDao;

@Service
public class TestService implements ITestService {
	// 2. DAO를 가져다 쓰는걸 만들어야함
	@Autowired
	public ITestDao iTestDao;

	@Override
	public List<HashMap<String, String>> getSellList() throws Throwable {

		return iTestDao.getSellList();
	}

	@Override
	// getSell매소드의 인자로 HashMap<String, String> param 받는거
	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.getSell(params);
	}

	@Override
	public int insertSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.insertSell(params);
	}

	@Override
	public int deleteSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.deleteSell(params);
	}

	@Override
	public int updateSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.updateSell(params);
	}

	@Override
	public List<HashMap<String, String>> getManagerList() throws Throwable {
		// TODO Auto-generated method stub
		return iTestDao.getManagerList();
	}

	@Override
	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.getManager(params);
	}

	@Override
	public int insertManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.insertManager(params);
	}

	@Override
	public int updateManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.updateManager(params);
	}

	@Override
	public int deleteManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.deleteManager(params);
	}

}

ITestDao.java

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

public interface ITestDao {

	public List<HashMap<String, String>> getSellList() throws Throwable;

	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable;

	public int insertSell(HashMap<String, String> params) throws Throwable;

	public int deleteSell(HashMap<String, String> params) throws Throwable;

	public int updateSell(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getManagerList() throws Throwable;

	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable;

	public int insertManager(HashMap<String, String> params) throws Throwable;

	public int deleteManager(HashMap<String, String> params) throws Throwable;

	public int updateManager(HashMap<String, String> params) throws Throwable;

}

TestDao.java

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class TestDao implements ITestDao {
	// 1.
	@Autowired
	public SqlSession sqlSession;

	@Override
	public List<HashMap<String, String>> getSellList() throws Throwable {
		// selectList("namespace.id"): 해당 namespace에 있는 id를 찾아서 조회 실행 목록을 받음
		// 목록으로 받을때 selectList
		return sqlSession.selectList("test.getSellList");
	}

	@Override
	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable {
		// selectOne(쿼리, 데이터) : 해당 쿼리에 데이터를 전달하고 단건 결과를 돌려받음
		return sqlSession.selectOne("test.getSell", params);
	}

	@Override
	public int insertSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.insert("test.insertSell", params);
	}

	@Override
	public int deleteSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.delete("test.deleteSell", params);
	}

	@Override
	public int updateSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.update("test.updateSell", params);
	}

	@Override
	public List<HashMap<String, String>> getManagerList() throws Throwable {
		// selectList("namespace.id"): 해당 namespace에 있는 id를 찾아서 조회 실행 목록을 받음
		// 목록으로 받을때 selectList
		return sqlSession.selectList("test.getManagerList");
	}

	@Override
	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable {
		// selectOne(쿼리, 데이터) : 해당 쿼리에 데이터를 전달하고 단건 결과를 돌려받음
		// selectOne이기 때문에 여러줄 들어오면 터짐
		return sqlSession.selectOne("test.getManager", params);
	}

	@Override
	public int insertManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.insert("test.insertManager", params);
	}

	@Override
	public int deleteManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.delete("test.deleteManager", params);
	}

	@Override
	public int updateManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.update("test.updateManager", params);
	}

}

sellList.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>
<style type="text/css">
table{
	border-collapse: collapse;
}

th, td {
	border: 1px solid #000;
	padding: 5px;
}

</style>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("tbody").on("click", "tr", function () {
		console.log($(this).attr("no"));
		$("#no").val($(this).attr("no"));
		
		$("#actionForm").submit();
	})
	
	$("#insertBtn").on("click", function () {
		location.href = "sellInsert";
	});
	
	
});

</script>
</head>
<body>
<form action="sellDetail" id="actionForm" method="post">
	<input type="hidden" id="no" name="no" /> 
	<input type="hidden" id="abc" name="abc" value="1234" />
</form>
<input type="button" value="추가" id="insertBtn" />
<br />
<table>
	<thead>
		<tr>
			<th>판매번호</th>
			<th>품목</th>
			<th>수량</th>
			<th>일자</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach var="data" items="${list}">
			<tr no="${data.SELL_NO}">
				<td>${data.SELL_NO}</td>
				<td>${data.ITEM_NAME}</td>
				<td>${data.COUNT}</td>
				<td>${data.SELL_DT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
</body>
</html>

sellDetail.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>
<script type="text/javascript" 
		src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("#listBtn").on("click", function() {
		$("#actionForm").attr("action","sellList"); 
		$("#actionForm").submit();
	});
	
	$("#deleteBtn").on("click", function () {
		if(confirm("삭제하시곘습니까?")){
			$("#actionForm").attr("action","sellRes"); 
			$("#actionForm").submit();
		}
	})
	
	$("#updateBtn").on("click", function () {
		$("#actionForm").attr("action","sellUpdate");
		$("#actionForm").submit();
	});
});

</script>
</head>
<body>
<!-- form action에서 #은 아무런 이동을 하지 않는다. -->
<form action="#" id="actionForm" method="post">
<!-- 상세보기에서는 삭제만 쓸거니 d를 박아줘도 됨, 수정이면 수정페이지로 이동할거니 -->
<!-- 이 페이지에서 수정도 같이하면 value에 값 비어두기 -->
	<input type="hidden" name="gbn" value="d"> <!-- selRes는 gbn을 받게 되어있어서 값을 추가해줘야함 -->
	<input type="hidden" name="no" value="${data.SELL_NO}">
</form>	
	판매번호: ${data.SELL_NO}<br/>
	품목: ${data.ITEM_NAME}<br/>
	수량: ${data.COUNT}<br/>
	일자: ${data.SELL_DT}<br/>
<input type="button" value="수정" id="updateBtn" />
<input type="button" value="삭제" id="deleteBtn" />
<input type="button" value="목록" id="listBtn" />
</body>
</html>

sellInsert.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("#listBtn").on("click", function () {
		history.back();
	});
	
	$("#insertBtn").on("click", function () {
		if($("#count").val() == ""){
			alert("수량을 입력하세요");
			$("#count").focus();
		} else if($("#count").val()*1 < 1){ // 문자열이기 때문에 *1 해줘야 숫자로 바뀜
			alert("수량은 1개 이상이어야 합니다");
			$("#count").focus();
		}
		else if($("#sellDt").val() == ""){
			alert("일자를 입력하세요");
			$("#sellDt").focus();
		} else {
			$("#actionForm").submit();
		}
	});
});

</script>
</head>
<body>
<!-- 번호는 시퀀스 쓸거기 때문에 받을 필요없음, 보여줄 필요 없음, 저장되야 글번호 보여지지 -->
<!-- select 전달하기 위해  name줘야함 -->
<!-- option value 지정해줘야함! -->
<form action="sellRes" id="actionForm" method="post">
<!-- gbn : 구분, 혹은 flag -->
<!-- 구분: i - insert, u - update, d - delete -->
<input type="hidden" name="gbn" value="i"/>
품목명
<select name="itemName">
	<option value="감자">감자</option>
	<option value="고구마">고구마</option>
	<option value="애호박">애호박</option>
	<option value="호박">호박</option>
	<option value="호박고구마">호박고구마</option>
</select>
<br />
수량 <input type="number" name="count" id="count" value="0" />
<br />
일자 <input type="date" name="sellDt" id="sellDt" />
<br />
</form>
<input type="button" value="등록" id="insertBtn">
<input type="button" value="목록" id="listBtn">
</body>
</html>

sellRes.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	
	// el tag를 script에서 사용시
	// 해당 위치에 값이 그대로 들어가기 때문에 보편적으로 ''를 달아서 문자열로 인식시킨 뒤 사용
	// ${res}해서  success가 들어올경우, success 이렇게되면 변수로 인식되서 "success" 이렇게 인식되게
	// "${res}"로 써줌
	switch("${res}"){
	case "success" : 
		if("${param.gbn}" == "u"){ // 수정이 성공했을 떄
			$("#goForm").submit();
		} else { // 등록, 삭제가 성공했을 떄
			location.href = "sellList" 
		}
		break;
	case "failed" : 
		alert("작업에 실패하였습니다.");
		history.back();
		break;
	case "error" : 
		alert("작업중 문제가 발생 하였습니다.");
		history.back();
		break;
	}
});
</script>
</head>
<body>
<form action="sellDetail" id="goForm" method="post">
	<input type="hidden" name="no" value="${param.no}" /> <!-- 전 화면에서 넘어오니까 param.no -->
</form>
</body>
</html>

sellUpdate.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	// 기존값으로 셀렉트박스 선택 내용 변경
	$("#itemName").val("${data.ITEM_NAME}");
	
	$("#listBtn").on("click", function () {
		history.back();
	});
	
	$("#updateBtn").on("click", function () {
		if($("#count").val() == ""){
			alert("수량을 입력하세요");
			$("#count").focus();
		} else if($("#count").val()*1 < 1){ // 문자열이기 때문에 *1 해줘야 숫자로 바뀜
			alert("수량은 1개 이상이어야 합니다");
			$("#count").focus();
		}
		else if($("#sellDt").val() == ""){
			alert("일자를 입력하세요");
			$("#sellDt").focus();
		} else {
			$("#actionForm").submit();
		}
	});
});

</script>
</head>
<body>
<!-- 번호는 시퀀스 쓸거기 때문에 받을 필요없음, 보여줄 필요 없음, 저장되야 글번호 보여지지 -->
<!-- select 전달하기 위해  name줘야함 -->
<!-- option value 지정해줘야함! -->
<form action="sellRes" id="actionForm" method="post">
<!-- gbn : 구분, 혹은 flag -->
<!-- 구분: i - insert, u - update, d - delete -->
<input type="hidden" name="gbn" value="u"/>
<input type="hidden" name="no" value="${data.SELL_NO}"/> <!-- 이 번호만 수정해라라는 조건 달기위해 필요 -->
판매번호 : ${data.SELL_NO}<br/>
품목명
<select name="itemName" id="itemName">
	<option value="감자">감자</option>
	<option value="고구마">고구마</option>
	<option value="애호박">애호박</option>
	<option value="호박">호박</option>
	<option value="호박고구마">호박고구마</option>
</select>
<br />
수량 <input type="number" name="count" id="count" value="${data.COUNT}" />
<br />
일자 <input type="date" name="sellDt" id="sellDt" value="${data.SELL_DT}" />
<br />
</form>
<input type="button" value="수정" id="updateBtn">
<input type="button" value="뒤로가기" id="listBtn">
</body>
</html>

 

managerList.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>
<style type="text/css">
table{
	border-collapse: collapse;
}

th, td {
	border: 1px solid #000;
	padding: 5px;
}

</style>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("tbody").on("click", "tr", function () {
		console.log($(this).attr("no"));
		$("#no").val($(this).attr("no"));
		
		$("#actionForm").submit();
	})
	
	$("#insertBtn").on("click", function () {
		location.href = "managerInsert";
	});
})

</script>
</head>
<body>
<form action="managerDetail" id="actionForm" method="post">
	<input type="hidden" id="no" name="no" /> 
</form>
<input type="button" value="추가" id="insertBtn" />

<table>
	<thead>
		<tr>
			<th>사원번호</th>
			<th>이름</th>
			<th>부서</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach var="data" items="${list}">
			<tr no="${data.EMP_NO}">
				<td>${data.EMP_NO}</td>
				<td>${data.NAME}</td>
				<td>${data.DEPT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
</body>
</html>

managerDetail.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>
<script type="text/javascript" 
		src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("#listBtn").on("click", function() {
		$("#actionForm").attr("action","managerList"); 
		$("#actionForm").submit();
	});
	
	$("#deleteBtn").on("click", function () {
		if(confirm("삭제하시곘습니까?")){
			$("#actionForm").attr("action","managerRes"); 
			$("#actionForm").submit();
		}
	})
	
	$("#updateBtn").on("click", function () {
		$("#actionForm").attr("action","managerUpdate");
		$("#actionForm").submit();
	});
});

</script>
</head>
<body>
<form action="#" id="actionForm" method="post">
	<input type="hidden" name="gbn" value="d"> <!-- selRes는 gbn을 받게 되어있어서 값을 추가해줘야함 -->
	<input type="hidden" name="no" value="${data.EMP_NO}">
</form>	
사번: ${data.EMP_NO}<br/>
이름: ${data.NAME}<br/>
부서: ${data.DEPT}<br/>
<input type="button" value="수정" id="updateBtn" />
<input type="button" value="삭제" id="deleteBtn" />
<input type="button" value="목록" id="listBtn" />
</body>
</html>

managerInsert.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("#listBtn").on("click", function () {
		history.back();
	});
	
	$("#insertBtn").on("click", function () {
		if($("#name").val() == ""){
			alert("이름을 입력하세요");
			$("#name").focus();
		}  else {
			$("#actionForm").submit();
		}
	});
});

</script>
</head>
<body>
<form action="managerRes" id="actionForm" method="post">
<!-- gbn : 구분, 혹은 flag -->
<!-- 구분: i - insert, u - update, d - delete -->
<input type="hidden" name="gbn" value="i"/>
이름
<input type="text" name="name" id="name" />
<br />
부서
<select name="deptName">
	<option value="영업1팀">영업1팀</option>
	<option value="영업2팀">영업2팀</option>
	<option value="영업3팀">영업3팀</option>
</select>
<br />
</form>
<input type="button" value="등록" id="insertBtn">
<input type="button" value="목록" id="listBtn">
</body>
</html>

managerRes.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	
	switch("${res}"){
	case "success" : 
		if("${param.gbn}" == "u"){ // 수정이 성공했을 떄
			$("#goForm").submit();
		} else { // 등록, 삭제가 성공했을 떄
			location.href = "managerList" 
		}
		break;
	case "failed" : 
		alert("작업에 실패하였습니다.");
		history.back();
		break;
	case "error" : 
		alert("작업중 문제가 발생 하였습니다.");
		history.back();
		break;
	}
});
</script>
</head>
<body>
<form action="managerDetail" id="goForm" method="post">
	<input type="hidden" name="no" value="${param.no}" />
</form>
</body>
</html>

managerUpdate.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>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	// 기존값으로 셀렉트박스 선택 내용 변경
	$("#name").val("${data.NAME}");
	
	$("#listBtn").on("click", function () {
		history.back();
	});
	
	$("#updateBtn").on("click", function () {
		if($("#name").val() == ""){
			alert("이름을 입력하세요");
			$("#name").focus();
		}  else {
			$("#actionForm").submit();
		} 
	});
});

</script>
</head>
<body>
<!-- 번호는 시퀀스 쓸거기 때문에 받을 필요없음, 보여줄 필요 없음, 저장되야 글번호 보여지지 -->
<!-- select 전달하기 위해  name줘야함 -->
<!-- option value 지정해줘야함! -->
<form action="managerRes" id="actionForm" method="post">
<!-- gbn : 구분, 혹은 flag -->
<!-- 구분: i - insert, u - update, d - delete -->
<input type="hidden" name="gbn" value="u"/>
<input type="hidden" name="no" value="${data.EMP_NO}"/> <!-- 이 번호만 수정해라라는 조건 달기위해 필요 -->
이름
<input type="text" name="name" id="name" />
<br />
부서
<select name="deptName">
	<option value="영업1팀">영업1팀</option>
	<option value="영업2팀">영업2팀</option>
	<option value="영업3팀">영업3팀</option>
</select>
<br />
</form>
<input type="button" value="수정" id="updateBtn">
<input type="button" value="뒤로가기" id="listBtn">
</body>
</html>

 

managerList.jsp

managerDetail.jsp

managerUpdate.jsp

managerInsert.jsp

728x90