교육 59일차
글 작성,상세보기,수정
M 테이블 실습
실습 순서
TestAMController
package com.spring.sample.web.testa.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.sample.common.bean.PagingBean;
import com.spring.sample.common.service.IPagingService;
import com.spring.sample.web.test.service.ITestLService;
import com.spring.sample.web.test.service.ITestMService;
@Controller
public class TestAMController {
@Autowired
public ITestMService iTestMService;
@Autowired
public ITestLService iTestLService;
@Autowired
public IPagingService iPagingService;
@RequestMapping(value="/testAMLogin")
public ModelAndView testALogin(ModelAndView mav) {
mav.setViewName("testa/testAMLogin");
return mav;
}
@RequestMapping(value="/testAMLogins",
method = RequestMethod.POST,
produces = "text/json;charset=UTF-8")
@ResponseBody // Spring에 view임을 제시, 오늘의 제일 중요한점 바로 웹으로 넘긴다. jsp 같은 역활을 한다.
public String testAMLogins(
HttpSession session,
@RequestParam HashMap<String, String> params) throws Throwable{
// ObjectMapper : 객체를 문자열로 전환 - Jackson 라이브러리
ObjectMapper mapper = new ObjectMapper();
//model은 데이터를 담고있는 것
// 데이터 보관용 map
// 모든 형태를 받기위해서 벨류값 형태 Object
Map<String, Object> modelMap = new HashMap<String, Object>();
HashMap<String, String> data = iTestLService.getM(params);
System.out.println("data:"+data);
if(data != null) { //사용자 정보가 있음
session.setAttribute("sMNo", data.get("M_NO"));
session.setAttribute("sMNm", data.get("M_NM"));
System.out.println(session.getAttribute("sMNm"));
modelMap.put("resMsg", "success");
} else { // 사용자 정보가 없음
modelMap.put("resMsg", "failed");
}
// "{"resMsg" : "success"}"
// writeValueAsString :객체를 문자열로 변환 , 받는 인자값이 형태가 object라 다 받을 수 있음
return mapper.writeValueAsString(modelMap);
}
@RequestMapping(value="/testAMList")
public ModelAndView testAMList(
@RequestParam HashMap<String, String> params,
ModelAndView mav) {
int page = 1;
if(params.get("page") != null) {
page = Integer.parseInt(params.get("page"));
}
mav.addObject("page", page);
mav.setViewName("testa/testAMList");
return mav;
}
@RequestMapping(value="/testAMLists",
method = RequestMethod.POST,
produces = "text/json;charset=UTF-8")
@ResponseBody
public String testAMLists(
@RequestParam HashMap<String, String> params) throws Throwable{
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> modelMap = new HashMap<String, Object>();
// 현재 페이지
int page = Integer.parseInt(params.get("page"));
// 총 게시글 수
int cnt = iTestMService.getMCnt(params);
// 페이징 정보 취득
PagingBean pb= iPagingService.getPagingBean(page, cnt);
//글번호 P 없으면 글번호
//게시글 시작번호, 종료번호 할당
params.put("startCnt", Integer.toString(pb.getStartCount()));
params.put("endCnt", Integer.toString(pb.getEndCount()));
// 목록 취득
List<HashMap<String, String>>list= iTestMService.getMList(params);
modelMap.put("list", list);
modelMap.put("pb", pb);
return mapper.writeValueAsString(modelMap);
}
@RequestMapping(value="/testAMLogout")
public ModelAndView testALogout(HttpSession session,
ModelAndView mav) {
session.invalidate();
mav.setViewName("redirect:testAMLogin");
return mav;
}
@RequestMapping(value ="/testAMWrite")
public ModelAndView testABWrite(ModelAndView mav) {
mav.setViewName("testa/testAMWrite");
return mav;
}
@RequestMapping(value="/testAMWrites",
method = RequestMethod.POST,
produces = "text/json;charset=UTF-8")
@ResponseBody
public String testAMWrites(
@RequestParam HashMap<String, String> params) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> modelMap = new HashMap<String, Object>();
try {
int cnt = iTestMService.addM(params);
if(cnt > 0) {
modelMap.put("msg", "success");
} else {
modelMap.put("msg", "failed");
}
} catch (Throwable e) {
e.printStackTrace();
modelMap.put("msg", "error");
}
return mapper.writeValueAsString(modelMap);
}
@RequestMapping(value="/testAM")
public ModelAndView testAM(
@RequestParam HashMap<String, String> params,
ModelAndView mav) throws Throwable {
HashMap<String, String> data = iTestMService.getM(params);
mav.addObject("data", data);
mav.setViewName("testa/testAM");
return mav;
}
//수정
@RequestMapping(value="/testAMUpdate")
public ModelAndView testAMUpdate(
@RequestParam HashMap<String, String> params,
ModelAndView mav) throws Throwable{
HashMap<String, String> data = iTestMService.getM(params);
mav.addObject("data", data);
System.out.println("data:"+data);
mav.setViewName("testa/testAMUpdate");
return mav;
}
@RequestMapping(value="/testAMUpdates",
method = RequestMethod.POST,
produces = "text/json;charset=UTF-8")
@ResponseBody
public String testAMUpdates(
@RequestParam HashMap<String, String> params) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> modelMap = new HashMap<String, Object>();
try {
int cnt = iTestMService.updateM(params);
if(cnt > 0) {
modelMap.put("msg", "success");
} else {
modelMap.put("msg", "failed");
}
} catch (Throwable e) {
e.printStackTrace();
modelMap.put("msg", "error");
}
return mapper.writeValueAsString(modelMap);
}
@RequestMapping(value="/testAMDeletes",
method = RequestMethod.POST,
produces = "text/json;charset=UTF-8")
@ResponseBody
public String testAMDeletes(
@RequestParam HashMap<String, String> params) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> modelMap = new HashMap<String, Object>();
try {
int cnt = iTestMService.deleteM(params);
if(cnt > 0) {
modelMap.put("msg", "success");
} else {
modelMap.put("msg", "failed");
}
} catch (Throwable e) {
e.printStackTrace();
modelMap.put("msg", "error");
}
return mapper.writeValueAsString(modelMap);
}
}
Service파일 과 Dao파일 M으로 만든 파일을 사용했다.
testAMList(목록)
<%@ 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>목록</title>
<style type="text/css">
.paging_wrap div{
display:inline-block;
padding: 5px;
margin-left: 3px;
margin-right: 3px;
border: 1px solid #444;
border-radius: 3px;
width: 60px;
cursor: pointer;
text-align: center;
}
</style>
<script type="text/javascript"
src="resources/script/jquery/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
if("${param.searchGbn}" != ""){
$("#searchGbn").val("${param.searchGbn}");
}
reloadList();
$("#loginBtn").on("click",function(){
location.href = "testAMLogin";
}); //loginBtn end
$("#logoutBtn").on("click",function(){
location.href = "testAMLogout";
}); //loginBtn end
$("#searchBtn").on("click", function(){
$("#page").val(1);
reloadList();
});
$(".paging_wrap").on("click","div",function(){
$("#page").val($(this).attr("page"));
reloadList();
});
//작성
$("#writeBtn").on("click",function(){
$("#actionForm").attr("action","testAMWrite");
$("#actionForm").submit();
});
$(".list_wrap tbody").on("click", "tr" ,function(){
$("#mNo").val($(this).attr("mno"));
$("#actionForm").attr("action","testAM");
$("#actionForm").submit();
}); //list end
}); //ready end
//목록 소환
function reloadList(){
var params = $("#actionForm").serialize();
//ajax
$.ajax({
url: "testAMLists",
type: "post",
dataType: "json",
data : params,
success: function(res){
console.log(res);
drawList(res.list);
drawPaging(res.pb);
},
error : function(request, status, error){
console.log(error);
}
});
}
//목록 그리기
function drawList(list){
var html= "";
" + + "
for(var d of list){
html += "<tr mno=\"" + d.M_NO + "\">";
html += "<td>" + d.M_NO +"</td>";
html += "<td>" + d.M_ID + "</td>";
html += "<td>" + d.M_NM + "</td>";
html += "<td>" + d.BD + "</td>";
html += "<td>" + d.DT + "</td>";
html += "</tr>";
}
//비동기시 항상 고정으로 뜨는 친구에게 이벤트 걸어야한다 필수
$(".list_wrap tbody").html(html);
}
//페이징 그리기
function drawPaging(pb){
var html = "";
html += "<div page=\"1\">처음</div>";
if($("#page").val() == "1"){
html += "<div page=\"1\">이전</div>";
} else{
html += "<div page=\""+($("#page").val() -1) +"\">이전</div>";
}
for(var i =pb.startPcount ; i <= pb.endPcount ; i++){
if($("#page").val() == i){
html += "<div class=\"on\" page=\"" + i + "\">" + i + "</div>";
} else{
html += "<div page=\"" + i + "\">" + i + "</div>";
}
}
if($("#page").val() == pb.maxPcount){
html += "<div page=\"" + pb.maxPcount + "\">다음</div>";
} else{
html += "<div page=\"" + ($("#page").val() * 1 + 1)+ "\">다음</div>";
}
html += "<div page=\"" + pb.maxPcount + "\">마지막</div>";
$(".paging_wrap").html(html);
}
</script>
</head>
<body>
<c:choose>
<c:when test="${empty sMNo}">
<input type="button" value="로그인" id="loginBtn"/>
</c:when>
<c:otherwise>
${sMNm}님 어서오슈.<input type="button" value="로그아웃" id="logoutBtn"/>
</c:otherwise>
</c:choose>
<div class="search_area">
<form action="#" id="actionForm" method="post">
<input type="hidden" id="mNo" name="mNo"/>
<input type="hidden" id="page" name="page" value="${page}"/>
<select id="searchGbn" name="searchGbn">
<option value="0">회원번호</option>
<option value="1">아이디</option>
<option value="2">이름</option>
</select>
<input type="text" name="searchTxt" value="${param.searchTxt}"/>
<input type="button" value="검색" id="searchBtn"/>
<input type="button" value="등록" id="writeBtn"/>
</form>
</div>
<div class="list_wrap">
<table>
<colgroup>
<col width="100px"/>
<col width="100px"/>
<col width="100px"/>
<col width="100px"/>
<col width="100px"/>
</colgroup>
<thead>
<tr>
<th>회원번호</th>
<th>아이디</th>
<th>이름</th>
<th>생일</th>
<th>가입일</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="paging_wrap"></div>
</body>
</html>
testAMWrite(작성)
<%@ 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>회원등록</title>
<style type="text/css">
#addForm input{
margin-bottom: 10px;
}
</style>
<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(){
$("#goForm").submit();
}); // list end
$("#addBtn").on("click",function(){
//입력된게 없는 경우
if($.trim($("#mId").val()) == ""){
alert("아이디를 입력해주세요");
$("#mId").focus;
} else if($.trim($("#mPw").val()) ==""){
alert("비밀번호를 입력해주세요");
$("#mPw").focus;
} else if($.trim($("#mPwRe").val()) != $.trim($("#mPw").val())){
alert("비밀번호가 일치하지 않습니다.");
$("#mPwRe").focus;
} else if($.trim($("#mNm").val()) ==""){
alert("이름 입력해주세요");
$("#mNm").focus;
} else if($.trim($("#mBr").val()) ==""){
alert("생일을 입력해주세요");
$("#mBr").focus;
} else{
var params =$("#addForm").serialize();
$.ajax({
url: "testAMWrites",
type: "post",
dataType: "json",
data: params,
success: function(res){
console.log(res)
console.log(params)
if(res.msg == "success"){
location.href = "testAMList";
} else if(res.msg == "failed"){
alert("등록에 실패하셨습니다.");
} else {
alert("에러발생.");
}
},
error: function(request, status, error){
console.log(error);
}
});
}
}); // add end
}); //ready end
</script>
</head>
<body>
<form action="testAMList" id="goForm" method="post">
<input type="hidden" name="page" value="${param.page}"/>
<input type="hidden" name="searchGbn" value="${param.searchGbn}"/>
<input type="hidden" name="searchTxt" value="${param.searchTxt}"/>
</form>
<form action="#" id="addForm" method="post" >
아이디<input type="text" id="mId" name="mId"/><br/>
비밀번호<input type="password" id="mPw" name="mPw"/><br/>
비밀번호확인<input type="password" id="mPwRe" name="mPwRe"/><br/>
이름<input type="text" id="mNm" name="mNm"/><br/>
생일<input type="date" id="mBr" name="mBr"/>
</form>
<input type="button" value="등록" id="addBtn"/>
<input type="button" value="목록으로" id="listBtn"/>
</body>
</html>
testAM(상세보기,삭제)
<%@ 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>상세보기</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(){
$("#sendForm").attr("action","testAMList");
$("#sendForm").submit();
}); //list end
$("#updateBtn").on("click",function(){
$("#sendForm").attr("action","testAMUpdate");
$("#sendForm").submit();
}); //updateBtn end
$("#deleteBtn").on("click", function(){
if(confirm("삭제하시겠습니까?")){
var params = $("#sendForm").serialize();
$.ajax({
url: "testAMDeletes",
type: "post",
dataType: "json",
data: params,
success: function(res){
console.log(res)
if(res.msg == "success"){
location.href="testAMList"
} else if(res.msg == "failed" ){
alert("작성에 실패하였습니다.");
} else {
alert("수정중 에러가 발생하였습니다.");
}
},
error: function(request, status, error){
console.log(error);
}
});
}
}); //deleteBtn
}); //ready end
</script>
</head>
<body>
<form action="#" id="sendForm" method="post">
<input type="hidden" name="mNo" value="${data.M_NO}"/>
<input type="hidden" name="page" value="${param.page}"/>
<input type="hidden" name="searchGbn" value="${param.searchGbn}"/>
<input type="hidden" name="searchTxt" value="${param.searchTxt}"/>
</form>
회원번호: ${data.M_NO}<br/>
아이디: ${data.M_ID}<br/>
이름: ${data.M_NM}<br/>
생일: ${data.BD}<br/>
가입일: ${data.DT}<br/>
<input type="button" value="수정" id="updateBtn"/>
<input type="button" value="삭제" id="deleteBtn"/>
<input type="button" value="목록으로" id="listBtn"/>
</body>
</html>
testAMUpadate(수정)
<%@ 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>수정</title>
<script type="text/javascript"
src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#backBtn").on("click",function(){
history.back();
});
$("#updateBtn").on("Keypress","input",function(){
if(event.keyCode == 13){
return false;
}
});
$("#updateBtn").on("click",function(){
if($.trim($("#mId").val()) == ""){
alert("아이디를 입력해주세요");
$("#mId").focus();
} else if($.trim($("#mBr").val()) == ""){
alert("생일을 입력해주세요");
$("#mBr").focus();
} else{
var params = $("#updateForm").serialize();
$.ajax({
url: "testAMUpdates",
type: "post",
dataType: "json",
data: params,
success: function(res){
console.log(res)
if(res.msg == "success"){
$("#updateForm").attr("action", "testAB");
$("#updateForm").submit();
} else if(res.msg == "failed" ){
alert("작성에 실패하였습니다.");
} else {
alert("수정중 에러가 발생하였습니다.");
}
},
error: function(request, status, error){
console.log(error);
}
});
}
});
});//ready end
</script>
</head>
<body>
<form action="#" id="updateForm" method="post">
<input type="hidden" name="page" value="${param.page}"/>
<input type="hidden" name="searchGbn" value="${param.searchGbn}"/>
<input type="hidden" name="searchTxt" value="${param.searchTxt}"/>
<input type="hidden" name="mNo" value="${data.M_NO}"/>
회원번호: ${data.M_NO} <br/>
아이디: ${data.M_ID} <br/>
이름<input type="text" id="mNm" name="mNm" value="${data.M_NM}"/><br/>
생일<input type="date" id="mBd" name="mBd" value="${data.BD}"/><br/>
가입일: ${data.DT}<br/>
</form>
<input type="button" value="수정" id="updateBtn"/>
<input type="button" value="뒤로가기" id="backBtn"/>
</body>
</html>
조금씩 익숙해지고 오류가 보이기시작한다.
트러블 슈팅을 모아서 정리해보자
Author And Source
이 문제에 관하여(교육 59일차), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@wogus216/교육-59일차저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)