*Ajax를 이용하여 새로고침(Reload) 하지 않아도 글 작성 시 밑에 조회가 되도록 구현해보자
*Redirect를 쓰지 않아야 한다. Redirect 시키면 새로고침 됨
개발 환경
톰캣 8.5, 이클립스, 오라클, JDK, Struts2, Spring2.0, iBatis
구현 순서
1. DB 생성 - iguest (테이블명)
2. DTO 생성 - GuestDTO.class
3. 페이징 처리를 위한 클래스 생성 - MyUtil.class (이전 페이징 처리와 조금 달라짐)
4. [jsp 페이지]
- 방명록 작성/조회 페이지 - guest.jsp
- DB에 접근하여 결과 뿌려주는 페이지 - list.jsp
5. Action 클래스 생성 - GuestAction.java
6. [iBatis]
- iguest_sqlMap.xml
- sqlMap_config.xml에 resource 등록 (iguest_sqlMap.xml)
7. [Struts2] struts 환경 설정 - struts-iguest.xml 생성 및 등록
8. Struts가 아닌 스프링에서 객체 생성 시 - action-Context.xml
1. DB 생성 - 사용할 iguest 테이블 생성
CREATE TABLE iguest(
num NUMBER(9),
name VARCHAR(25),
email VARCHAR(50),
content VARCHAR(4000), - 한글은2000자제한
ipAddr VARCHAR(50),
created DATE,
CONSTRAINT pk_iguest_num
PRIMARY KEY(num));
컬럼 수 - 6개
2. DTO 생성 - GuestDTO.class
package com.iguest;
public class GuestDTO {
//DB저장 영역
private int num;
private String name;
private String email;
private String content;
private String ipAddr;
private String created;
private int listNum;
private String pageNum;
// getter, setter 생략
}
3. 페이징 처리를 위한 클래스 생성 - MyUtil.class (미완)
package com.util;
import org.springframework.stereotype.Service;
//page 처리하는 클래스
//@Service("myUtil")
public class MyUtil {
//전체 페이지 수 구하기
public int getPageCount(int numPerPage, int dataCount) {
int pageCount = 0;
// 한 페이당 몇개의 글이 필요한지 나옴
pageCount = dataCount/numPerPage;
if(dataCount%numPerPage!=0)
pageCount++;
return pageCount;
}
// 이전에 쓰던 listUrl (list.jsp? 이렇게 url 넘어오던 것) 이 매개변수로 필요 없음
// => listPage() 함수를 호출할 것이기 때문
// currentPage : 현재 표시할 페이지
// totalPage : 전체 페이지의 갯수
public String pageIndexList(int currentPage, int totalPage) {
int numPerBlock = 3;
int currentPageSetup;
int n;
int page;
String strList = "";
if(currentPage==0)
return "";
// 표시할 첫 페이지 (공식)
currentPageSetup = (currentPage/numPerBlock)*numPerBlock;
if(currentPage%numPerBlock==0)
currentPageSetup = currentPageSetup-numPerBlock;
// 1페이지 만드는 과정
// if(totalPage>numPerBlock && currentPageSetup>0) {
// //listPage() 함수를 호출할 것임
// //1 이라는 숫자를 클릭하면 listPage에 매개변수 1 담아서 보낸다
// strList = "<a onclick='listPage(1);'>1</a> ";
// }
//자바스크립트에 listPage() 라는 function을 정의하여 사용할 것이므로 a 태그에 작성
// [이전] 만들기
// 총 페이지 수가 numPerBlock 이상인 경우 이전 numPerBlock(게시글 3개)를 보여줌
// n = currentPage - numPerBlock; // 5 - 3 = 2 => 쌤이 써주신건데 이거로 하니깐 안됨..
n = currentPageSetup;
if(totalPage>numPerBlock && currentPageSetup>0) {
strList +=
"[<a onclick='listPage(" + n + ");'>◀</a>] ";
}
//바로가기 페이지
page = currentPageSetup + 1; // 5 + 1 => 6부터 찍으면 된다 (6,7,8,9,10)
while( page<=totalPage && page<=(currentPageSetup+numPerBlock)) {
//내가 클릭한 숫자가 현재 페이지랑 같다면,
if (page == currentPage) {
strList += "<font color=\"Fuchsia\">" + page +
"</font> ";
} else {
// 클릭한 숫자가 현재 페이지가 아니라면 listPage(); 호출
strList +=
"<a onclick='listPage(" + page + ");'>"
+ page + "</a> ";
}
page++; //만약 내가 3번을 찍었으면 -> 그 다음 4번도 다시 반복해서 검사
}
//[다음] 만들기
n = currentPageSetup + numPerBlock + 1;
if(totalPage-currentPageSetup>numPerBlock) {
strList +=
"[<a onclick='listPage(" + n + ");'>▶</a>]";
}
/*
// 마지막 페이지
if (totalPage>numPerBlock &&
currentPageSetup + numPerBlock < totalPage) {
strList +=
"<a onclick='listPage(" + totalPage + ");'>"
+ totalPage + "</a>";
}*/
//링크되어 있는 String을 보내줌
return strList;
}
}
4. jsp 페이지 생성 - 방명록 작성/조회 페이지 - guest.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>방명록 만들기(ajax)</title>
<link rel="stylesheet" href="<%=cp %>/data/css/style.css" type="text/css">
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
// 화면이 호출되면 표시할 첫 페이지
$(function(){
listPage(1);
});
// 새로고침X
$(document).ready(function(){
$("#sendButton").click(function(){
// javascript는 document.getElementById 이렇게 접근했었음
// jquery는 사용자가 아래서 입력한 데이터를 이렇게 받아옴
var params = "name=" + $("#name").val()
+ "&email=" + $("#email").val()
+ "&content=" + $("#content").val();
$.ajax({
// 입력창 보내는거니깐 post형태로
// 현재 struts2+spring로 연결하는거임
type:"POST",
url:"<%=cp%>/guest/created.action",
data:params,
success:function(args){
// 결과 데이터는 이미 표로 가공된 상태로 올 것임 (방명록 글 창)
$("#listData").html(args);
//새로고침한게 아니라 ajax부분만 바뀌기 때문에, 사용자가 [등록하기] 누르고 나면
// 입력창에 사용자가 입력한 데이터가 그대로 남아있음
// => input 태그에 입력된 데이터를 없애주는 소스가 필요 (초기화)
$("#name").val("");
$("#email").val("");
$("#content").val("");
$("#name").focus; // 다 지우고 name에다가 커서 갖다놓기
},
beforeSend:showRequest, // 보내기전에 실행
error:function(e) {
alert(e.responseText); // 갔다와서 에러가 나면 알람을 띄워라
}
}); // ...end $.ajax
});
});
function showRequest() {
// 사용자가 입력한 데이터를 공백 제거하고 가져오기
var name = $.trim($("#name").val());
var email = $.trim($("#email").val());
var content = $.trim($("#content").val());
if(!name) {
alert("\n이름을 입력하세요!");
$("#name").focus;
return false;
}
if (!email) {
alert("\n이메일을 입력하세요!");
$("#email").focus;
return false;
}
if (!content) {
alert("\n내용을 입력하세요!");
$("#content").focus;
return false;
}
if (!content.length > 200) {
alert("\n내용을 200자까지만 입력 가능합니다!");
$("#content").focus;
return false;
}
// true가 반환되어야만, 서버로 값을 보냄
return true;
}
// 3페이지 누르면 3페이지 뜨게
// 페이징처리를 js로
function listPage(page) {
var url = "<%=cp%>/guest/list.action";
//jQuery로만 ajax를 만들 때 사용
$.post(url,{pageNum:page},function(args) {
// js특징중하나
//url 에 pageNum,page를 가지고 들어가서
//결과를 바로 받아온다 (보내는애와 받는애가 같이 있는 구조)
$("#listData").html(args);
});
$("#listData").show(); // display:block으로 프로퍼티를 설정한 것과 동일한 효과
}
// 삭제할번호, 페이징처리를 위한 pageNum을 매개변수로 받아야함
// 새로고침X
function deleteData(num,page) {
var url = "<%=cp%>/guest/deleted.action";
// *jQuery로만 ajax를 만들 때 사용하는 방법*
// 변수명:데이터
$.post(url,{num:num,pageNum:page},function(args) {
//결과를 바로 받아온다 (보내는애와 받는애가 같이 있는 구조)
// 삭제 후 댓글창 결과(args) 뿌려줌
$("#listData").html(args);
});
$("#listData").show();
}
</script>
</head>
<body>
<br/><br/>
<table width="600" border="2" cellpadding="0" cellspacing="0"
bordercolor="#e6d4a6" align="center">
<tr height="40">
<td style="padding-left: 20px;">방 명 록</td>
</tr>
</table>
<br/><br/>
<table width="600" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td width="600" colspan="4" height="3" bgcolor="#e6d4a6"></td>
</tr>
<tr>
<td width="60" height="30" bgcolor="#eeeeee" align="center">작성자</td>
<td width="240" height="30" style="padding-left: 10px;">
<input type="text" id="name" size="35" maxlength="20" class="boxTF"/>
</td>
<td width="60" height="30" bgcolor="#eeeeee" align="center">
이메일
</td>
<td width="240" height="30" style="padding-left: 10px;">
<input type="text" id="email" size="35" maxlength="50" class="boxTF"/>
</td>
</tr>
<tr>
<td width="600" colspan="4" height="1" bgcolor="#e6d4a6"></td>
</tr>
<tr>
<td width="60" height="30" bgcolor="#eeeeee" align="center">
내용
</td>
<td width="540" colspan="3" style="padding-left: 10px;">
<textarea rows="3" cols= "84" class="boxTA" style="height: 50px;" id="content">
</textarea>
</td>
</tr>
<tr>
<td width="600" colspan="4" height="1" bgcolor="#e6d4a6"></td>
</tr>
<tr>
<td width="600" height="30" colspan="4" align="right" style="padding-right: 15px;">
<input type="button" value="등록하기" class="btn2" id="sendButton"/>
</td>
</tr>
</table>
<br/><br/>
<!-- 방명록 글 (=댓글창) 뜨는 부분 -->
<span id="listData" style="display: none">
</span>
<br/>
</body>
</html>
결과 화면
글 아무것도 안 올렸을 때
글 올렸을 때
'Ajax & jQuery' 카테고리의 다른 글
Ajax - 댓글 기능이 있는 게시판 만들기(미) (0) | 2019.10.27 |
---|---|
Ajax(5) - Document Object Model (DOM), DOM API를 이용한 XML 파싱 (pdf파일로부터 내용 더 보완하기) (0) | 2019.10.24 |
Ajax(4) - JSON형식 데이터를 읽어와 Javascript의 객체 생성 하기 (0) | 2019.10.23 |
Ajax(3) - CSV 형식 데이터 읽기, 검색 시 제시어 기능 (0) | 2019.10.23 |
JQuery 셋팅 및 예제 (10.18필기보고보완) (0) | 2019.10.23 |