게시글 본문내용
|
다음검색
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="ctxPath" value="${pageContext.request.contextPath}"/> <c:set var="LF" value="\n" scope="page" /> <c:set var="BR" value="<br>" scope="page" /> <c:set var="First" value="<<" scope="page" /> <c:set var="Last" value=">>" scope="page" /> <c:set var="Prev" value="◁" scope="page" /> <c:set var="Next" value="▷" scope="page" /> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax1.jsp</title> <%@ include file="/include/bs4.jsp" %> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> 'use strict'; function idCheck1() { //let mid = document.getElementById("mid").value;//html,jsp //let mid = '${mid}';//jstl(모든 request parameter 문자는 default로 공백처리됨) let mid = $("#mid").val();//jquery(ajax framework) if (''==mid || ''==mid.trim()) { alert('아이디를 입력하세요.'); $("#mid").focus(); return false; } let arr = []; arr.push('a'); arr.push('b'); arr.push('c'); alert('arr.length='+arr.length); let params = { mid: mid, mid2: '', testArr: arr,//배열로 넘기고 서블릿에서 getparametervalues배열로 받으면null처리된다 }; //jquery함수 //$(document).ready(function() { //}); //aJax함수 $.ajax({ type: "get", //전송방식(get,post,enctype(화일전송용)) url: "${ctxPath}/ajaxIdSearch", //비동기식aJax는 확장자패턴은 편법으로 사용되며, url패턴으로 사용함 data: params, contextType: "application/json", //charset: "utf-8", //xml에서 설정했으면 생략 success: function(name) { //response로 앞에서 준 파라미터는 function함수의 파라미터로 받는다 $("#demo").html(name);//$('#demo').innerHtml=name 와 같음 }, error: function() { alert("서버 요청 실패~~"); } }); } function idCheck2() { let mid = $("#mid").val(); if (''==mid) { alert("아이디를 입력하세요"); $("#mid").focus(); return false; } $.ajax({ type: "post", url: "${ctxPath}/ajaxIdSearch2",//서블릿에서 dispatcher로 이동할 jsp지정안함 data: {mid : mid}, //contextType: "application/json",//생략가능(default ?) //charset: "utf-8", //xml에서 설정했으면 생략 success: function(resData) { $("#demo").html(resData);//$('#demo').innerHtml=resData 와 같음 }, error: function() { alert("전송 실패~~"); } }); } function idCheck3() { let mid = $("#mid").val(); if (""==mid) { alert("아이디를 입력하세요"); $("#mid").focus(); return false; } $.ajax({ type: "post", url: "${ctxPath}/ajaxIdSearch3",//서블릿에서 dispatcher로 이동할 jsp지정안함 data: {mid : mid}, contextType: "application/json",//생략가능(default ?) //charset: "utf-8", //xml에서 설정했으면 생략 success: function(resData) { $("#demo").html(resData);//$('#demo').innerHtml=resData 와 같음 let arrData = resData.split("/");//response로 받은 파라미터는 1개만 넘어옴, 여러개 받고자 할 때는 편집해서 보낼 것(객체로 못받음,null도 못받음). if (null!=arrData[0] && null!=arrData[1] && null!=arrData[2] && null!=arrData[3]) userSearch(arrData[0], arrData[1], arrData[2], arrData[3]); }, error: function() { alert("전송 실패~~"); } }); } //유저 등록 function userInput() { let mid = $("#userId").val(); let name = $("#userName").val(); let age = $("#userAge").val(); let address = $("#userAddress").val(); if (''==mid || ''==name) { alert('아이디/성명/나이/주소를 입력하세요.'); $("#userId").focus(); return false; } let query = { mid : mid, name : name, age : age, address : address }; $.ajax({ type: "post", url: "${ctxPath}/ajaxUserInput", data: query, success: function(data) { if ('1' == data) { alert('자료를 등록했습니다'); location.reload(); } else if ('0' == data){ alert('등록 실패'); } }, error: function() { alert('전송오류~~'); } }); } //전체유저 조회 function userList() { location.href = "${ctxPath}/userList.st"; } //개별자료조회 출력 function userSearch(mid, name, age, address) { $("#userId").val(mid); $("#userName").val(name); $("#userAge").val(age); $("#userAddress").val(address); } function userDelete(idx) { if ( !confirm('삭제할까요?') ) return false; $.ajax({ type: "post", url: "${ctxPath}/ajaxUserDelete", data: {idx : idx}, success: function(data) { if ('1' == data) { alert('자료를 삭제했습니다'); location.reload(); } else { alert('삭제 실패~~'); } }, error: function() { alert('전송오류'); } }); } </script> <style> th { background-color: #eee; text-align: center; } </style> </head> <body> <%@ include file="/include/header_home.jsp" %> <%@ include file="/include/nav.jsp" %> <p><br></p> <div class="container"> <h2 class="text-center">AJax연습</h2> <form name="searchForm"> 아이디 : <input type="text" name="mid" id="mid"/> <input type="button" value="아이디검색1" xxxxonclick="idCheck1()" class="btn btn-success"/> <input type="button" value="아이디검색2" xxxxonclick="idCheck2()" class="btn btn-success"/> <input type="button" value="아이디검색3" xxxxonclick="idCheck3()" class="btn btn-warning"/> </form> <div>출력 결과 : <span id="demo"></span></div> <hr/> <br> <form> <table class="table table-bordered"> <tr> <td colspan="2" class="text-center">User 가입 폼</td> </tr> <tr> <th>아이디</th> <td><input type="text" name="userId" id="userId" class="form-control"/></td> </tr> <tr> <th>성명</th> <td><input type="text" name="userName" id="userName" class="form-control"/></td> </tr> <tr> <th>나이</th> <td><input type="text" name="userAge" id="userAge" class="form-control"/></td> </tr> <tr> <th>주소</th> <td><input type="text" name="userAddress" id="userAddress" class="form-control"/></td> </tr> <tr> <td colspan="2" class="text-center"> <input type="button" value="유저등록" xxxxonclick="userInput()" class="btn btn-info"/> <input type="reset" value="다시입력" class="btn btn-info"/> <input type="button" value="유저전체보기" xxxxonclick="userList()" class="btn btn-info"/> </td> </tr> </table> </form> <hr/> <br> <h3 class="text-center">User 전체 목록</h3> <!-- 페이징 처리 시작 --> <div class="col text-right"> <c:if test="${pageNo > 1}"> <a href='${ctxPath}/userList.st?pageNo=1' title='first'>${First}</a> <a href='${ctxPath}/userList.st?pageNo=${pageNo - 1}' title='prev'>${Prev}</a> </c:if> ${pageNo}Page / ${totPage}Pages <c:if test="${pageNo != totPage}"> <a href='${ctxPath}/userList.st?pageNo=${pageNo + 1}' title='next'>${Next}</a> </c:if> <a href='${ctxPath}/userList.st?pageNo=${totPage}' title='last'>${Last}</a> </div> <!-- 페이징 처리 끝 --> <table class="table table-hover"> <tr> <th>번호</th><th>아이디</th><th>성명</th><th>나이</th><th>주소</th><th>조회/삭제</th> </tr> <c:forEach var="vo" items="${vos}"> <tr> <td class="text-center">${curScrStartNo}</td> <td>${vo.mid }</td> <td>${vo.name }</td> <td class="text-center">${vo.age }</td> <td>${vo.address }</td> <td class="text-center"> <a href="xxxxjavascript:userSearch('${vo.mid}','${vo.name}','${vo.age}','${vo.address}');" class="btn btn-secondary btn-sm">조회</a> <a href="xxxxjavascript:userSearch('${vo.mid}','${vo.name}','${vo.age}','${vo.address}');xxxxjavascript:userDelete('${vo.idx}');" class="btn btn-secondary btn-sm">삭제</a> </td> </tr> <c:set var="curScrStartNo" value="${curScrStartNo-1}"/> </c:forEach> </table> <!-- 블럭페이징 처리 시작 --> <div class="text-center"> <c:if test="${pageNo > 1}"> [<a href='${ctxPath}/userList.st?pageNo=1' title='first'>첫페이지</a>] </c:if> <c:if test="${curBlock > 0}"> [<a href='${ctxPath}/userList.st?pageNo=${(curBlock-1)*blockSize+1}' title='prevBlock'>이전블록</a>] </c:if> <c:set var="isBreak" value="false"/> <c:forEach var="i" begin="${(curBlock*blockSize)+1}" end="${(curBlock*blockSize)+blockSize}"> <c:if test="${i <= totPage && i == pageNo}"> [<a href="${ctxPath}/userList.st?pageNo=${i}"><font color='red'><b>${i}</b></font></a>] </c:if> <c:if test="${i <= totPage && i != pageNo}"> [<a href="${ctxPath}/userList.st?pageNo=${i}">${i}</a>] </c:if> </c:forEach> <c:if test="${curBlock < lastBlock}"> [<a href='${ctxPath}/userList.st?pageNo=${(curBlock+1)*blockSize+1}' title='nextBlock'>다음블록</a>] </c:if> [<a href='${ctxPath}/userList.st?pageNo=${totPage}' title='last'>마지막페이지</a>] </div> <!-- 블럭페이징 처리 끝 --> </div> <%@ include file="/include/footer.jsp" %> </body> </html> | cs |
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 | package study2; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import common.Paging; import study2.ajax.database.UserDAO; import study2.ajax.database.UserVO; public class Ajax1Command implements StudyInterface { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserDAO dao = new UserDAO(); Paging paging = new Paging(request, response); int pageNo = request.getParameter("pageNo")==null?1:Integer.parseInt(request.getParameter("pageNo")); paging.setPaging(pageNo, dao.totRecCnt(), 3, 3); List<UserVO> vos = dao.searchUserList(paging.getStartIndexNo(), paging.getPageSize()); request.setAttribute("vos", vos); } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | package common; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Paging { private HttpServletRequest request; private HttpServletResponse response; private int startIndexNo = 0; private int pageSize = 0; /** * 페이징 생성자 * @param request HttpServletRequest * @param response HttpServletResponse * @throws ServletException * @throws IOException */ public Paging(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.request = request; this.response = response; } /** * 페이징 정보를 산출하여 REQUEST 객체에 페이징 설정 * @param pageNo 현재의 페이지 번호 * @param totalRecordSize 목록의 총 레코드 갯수 * @param pagingRecordSize 각 페이징할 목록의 레코드 갯수 * @param blockingSize 페이징할 블록 갯수 */ public void setPaging(int pageNo, int totalRecordSize, int pagingRecordSize, int blockingSize) { /* * 페이징 처리 * 0. 현 페이지 구하기 : page = @param pageNo * 1. 한 페이지 분량을 정한다 : pageSize = 5 * 2. 총 레코드 건수를 구하기 : totRecCnt = @param totalRecordCnt * 3. 총 페이지 수 구하기 : totPage => totRecCnt % pageSize (몫의 정수값이 0이면 정수, 몫의 정수값이 아니면 정수값 + 1) * 4. 현재페이지의 시작 인덱스 : startIndexNo => (page -1) * pageSize * 5. 화면에 보이는 방문소감의 시작번호 : curScrStartNo = totRecCnt - startIndexNo * 6. 블록페이징처리 */ //0. 현 페이지 int page = pageNo; //1. 한 페이지 분량 this.pageSize = pagingRecordSize; //2. 총 레코드 건수 int totRecCnt = totalRecordSize; //3. 총 페이지 수 int totPage = (totRecCnt % pageSize)==0 ? (totRecCnt / pageSize) : (totRecCnt / pageSize)+1; //4. 현재페이지 시작 인덱스 this.startIndexNo = (page -1) * pageSize; //5. 방문소감의 시작번호 int curScrStartNo = totRecCnt - startIndexNo; //6. 블록페이징처리시 아래 내용 추가 (한블럭에 3page씩 보여준다) : blockSize int blockSize = blockingSize; //7. 현재 블럭 위치 (첫번째 블럭 = 0) : curBlock int curBlock = (page - 1) / blockSize; //8. 마지막 블럭 : lastBlock int lastBlock = (totPage % blockSize)==0 ? (totPage / blockSize) - 1 : (totPage / blockSize); request.setAttribute("curScrStartNo", curScrStartNo); request.setAttribute("pageNo", pageNo); request.setAttribute("totPage", totPage); //request.setAttribute("pageSize", pageSize); request.setAttribute("blockSize", blockSize); request.setAttribute("curBlock", curBlock); request.setAttribute("lastBlock", lastBlock); } /** * 한 페이징에 표시할 레코드 시작번호 취득 * @return startIndexNo */ public int getStartIndexNo() { return this.startIndexNo; } /** * 한 페이지 분량 취득 * @return pageSize */ public int getPageSize() { return this.pageSize; } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | package study2; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("*.st") public class StudyController extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StudyInterface command = null; String viewPage = "/WEB-INF"; String uri = request.getRequestURI(); String com = uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf(".")); if (com.equals("el1")) { viewPage += "/study2/el_JSTL/el1.jsp"; } else if (com.equals("el2")) { viewPage += "/study2/el_JSTL/el2.jsp"; } else if (com.equals("jstl1")) { viewPage += "/study2/el_JSTL/jstl1.jsp"; } else if (com.equals("jstl2")) { viewPage += "/study2/el_JSTL/jstl2.jsp"; } else if (com.equals("jstl3")) { viewPage += "/study2/el_JSTL/jstl3.jsp"; } //nav 메뉴에서 비밀번호 암호화 첫화면에 이동 else if (com.equals("shaPass")) { viewPage += "/study2/sha/shaPass.jsp"; } //암호화한 pwd를 갖고 이동 else if (com.equals("shaPassOk")) { command = new ShaPassOkCommand(); command.execute(request, response); viewPage += "/study2/sha/shaPass.jsp"; } //Ajax1-UserList else if (com.equals("userList")) { command = new Ajax1Command(); command.execute(request, response); viewPage += "/study2/ajax/ajax1.jsp"; } request.getRequestDispatcher(viewPage).forward(request, response); } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package study2.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import study2.ajax.database.UserDAO; import study2.ajax.database.UserVO; @WebServlet("/ajaxUserInput") public class AjaxUserInput extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserDAO dao = new UserDAO(); String mid = request.getParameter("mid"); String name = request.getParameter("name"); int age = 0; if (null!=request.getParameter("age") && !request.getParameter("age").trim().equals("")) age = Integer.parseInt(request.getParameter("age")); String address = request.getParameter("address"); if (null == mid || null == name) { response.getWriter().write("0");//insert res = 0(등록실패) return; } //아이디 중복 체크-여기서는 그냥 회원정보가져온 vo의 mid로 비교 UserVO vo = dao.search(mid); if (null != vo && vo.getMid().equals(mid)) { response.getWriter().write("0");//insert res = 0(등록실패) return; } UserVO insertVO = new UserVO(); insertVO.setMid(mid); insertVO.setName(name); insertVO.setAge(age); insertVO.setAddress(address); int res = dao.insert(insertVO); response.getWriter().write(String.valueOf(res));//insert res = 1(등록성공) , 0(등록실패<sql exception>) } } | cs |
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 | package study2.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import study2.ajax.database.UserDAO; @WebServlet("/ajaxUserDelete") public class AjaxUserDelete extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (null == request.getParameter("idx") || request.getParameter("idx").trim().equals("")) { response.getWriter().write("0"); return; } int idx = Integer.parseInt(request.getParameter("idx")); UserDAO dao = new UserDAO(); int res = dao.delete(idx); response.getWriter().write(String.valueOf(res)); } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 | package study2.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import study2.ajax.database.UserDAO; import study2.ajax.database.UserVO; @WebServlet("/ajaxIdSearch")//url패턴 public class AjaxIdSearch extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mid = request.getParameter("mid"); String mid2 = request.getParameter("mid2"); String[] testArr = (String[])request.getParameterValues("testArr"); System.out.printf("mid=%s mid2=%s \n", mid, mid2); System.out.println("testArr=" + testArr); String name = ""; if (null == mid) { name = "id가 null로 넘어왔습니다"; response.getWriter().write(name); return; } UserVO vo = new UserDAO().search(mid); if (null == vo) { name = "찾는 자료가 없습니다"; } else { name = vo.getName(); } //ajax는 자기가 req,res하므로(정해져있다?) request.getRequestDispatcher("갈 주소로 보내기")는 하지않는다 //response.getWriter()만 있으면 된다 PrintWriter() 객체 생성은 하지않는다 response.getWriter().write(name); } } | cs |
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 32 33 34 35 36 37 38 | package study2.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import study2.ajax.database.UserDAO; import study2.ajax.database.UserVO; @WebServlet("/ajaxIdSearch2")//url패턴 public class AjaxIdSearch2 extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mid = request.getParameter("mid"); if (null == mid) { response.getWriter().write("id가 null로 넘어왔습니다"); return; } UserVO vo = new UserDAO().search(mid); if (null==vo) { response.getWriter().write("찾는 자료가 없습니다."); return; } //ajax는 자기가 req,res하므로(정해져있다?) request.getRequestDispatcher("갈 주소로 보내기")는 하지않는다 //response.getWriter()만 있으면 된다 PrintWriter() 객체 생성은 하지않는다 String name = vo.getName(); response.getWriter().write(name); } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package study2.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import study2.ajax.database.UserDAO; import study2.ajax.database.UserVO; @WebServlet("/ajaxIdSearch3")//url패턴 public class AjaxIdSearch3 extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mid = request.getParameter("mid"); String data = null; if (null == mid) { data = "id가 null로 넘어왔습니다"; response.getWriter().write(data); return; } UserVO vo = new UserDAO().search(mid); String name = "", address = ""; int age = 0; if (null == vo) { data = "찾는 데이타가 없음(서블릿에서 ajax화면으로 전송시 null로는 전송할 수 없음)"; } else { mid = vo.getMid(); name = vo.getName(); age = vo.getAge(); address = vo.getAddress(); //ajax는 자기가 req,res하므로(정해져있다?) request.getRequestDispatcher("갈 주소로 보내기")는 하지않는다 //response.getWriter()만 있으면 된다 PrintWriter() 객체 생성은 하지않는다 data = mid + "/" + name + "/" + age + "/" + (address==null?"":address); } System.out.println("data="+data); response.getWriter().write(data); //문자로만 보냄.객체로는 못넘김 } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package study2.ajax.database; public class UserVO { private int idx; private String mid; private String name; private int age; private String address; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "UserVO [address=" + address + ", age=" + age + ", idx=" + idx + ", mid=" + mid + ", name=" + name + ", getAddress()=" + getAddress() + ", getAge()=" + getAge() + ", getIdx()=" + getIdx() + ", getMid()=" + getMid() + ", getName()=" + getName() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } } | cs |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | package study2.ajax.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import conn.MysqlConn; public class UserDAO { private final MysqlConn instance = MysqlConn.getInstance(); private final Connection conn = instance.getConn(); private PreparedStatement pstmt = null; private ResultSet rs = null; private UserVO vo = null; private String sql = new String(""); //페이징 총 레코드(게시판목록)건수 public int totRecCnt() { int totRecCnt = 0; try { sql = "select count(*) as totRecCnt from user"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); rs.next(); //ResultSet레코드움직이기(count함수는 무조건 0값조차 가져옴) totRecCnt = rs.getInt("totRecCnt"); } catch (SQLException e) { e.getMessage(); } finally { instance.rsClose(); instance.pstmtClose(); } return totRecCnt; } //User 목록 조회 public List<UserVO> searchUserList(int startIndexNo, int pageSize) { List<UserVO> vos = new ArrayList<>(); try { sql = "select * from user order by idx desc limit ?, ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, startIndexNo); pstmt.setInt(2, pageSize); rs = pstmt.executeQuery(); while (rs.next()) { vo = new UserVO(); vo.setIdx(rs.getInt("idx")); vo.setMid(rs.getString("mid")); vo.setName(rs.getString("name")); vo.setAge(rs.getInt("age")); vo.setAddress(rs.getString("address")); vos.add(vo); } } catch (SQLException e) { System.out.println("SQL 에러 : " + e.getMessage()); } finally { instance.pstmtClose(); instance.rsClose(); } return vos; } public UserVO search(String mid) { UserVO vo = null; try { sql = "select * from user where mid = ? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, mid); rs = pstmt.executeQuery(); if (rs.next()) { vo = new UserVO(); vo.setIdx(rs.getInt("idx")); vo.setMid(rs.getString("mid")); vo.setName(rs.getString("name")); vo.setAge(rs.getInt("age")); vo.setAddress(rs.getString("address")); } } catch (SQLException e) { System.out.println("SQL 에러 : " + e.getMessage()); } finally { instance.pstmtClose(); instance.rsClose(); } return vo; } //User 등록 public int insert(UserVO vo) { int res = 0; try { sql = "insert into user values ( default, ?, ?, "; if (0 == vo.getAge()) { sql += " default, "; } else { sql += " ?, "; } sql += " ? )"; pstmt = conn.prepareStatement(sql); int idx = 0; pstmt.setString(++idx, vo.getMid()); pstmt.setString(++idx, vo.getName()); if (0 < vo.getAge()) { pstmt.setInt(++idx, vo.getAge()); } pstmt.setString(++idx, vo.getAddress()); res = pstmt.executeUpdate(); } catch(SQLException e) { System.out.println("SQL 에러 : " + e.getMessage()); } finally { instance.pstmtClose(); } return res; } public int delete(int idx) { int res = 0; try { sql = "delete from user where idx = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, idx); res = pstmt.executeUpdate(); } catch(SQLException e) { System.out.println("SQL 에러 : " + e.getMessage()); } finally { instance.pstmtClose(); } return res; } } | cs |
첫댓글 꾸준히 좋은모습 보기 좋습니다.
페이징처리도 아주 잘 되었고요.
계속 좋은 모습 기대합니다. 수고하셨습니다.