폴더 구성
context.xml
<?xml version="1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/oracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@192.168.0.51:1521:orcl"
username="user03"
password="pass01"
maxTotal="20"
maxWaitMillis="5000" />
<Resource
name="jdbc/oracle1"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="scott"
password="tiger"
maxTotal="20"
maxWaitMillis="5000" />
</Context>
json.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "org.json.simple.JSONArray" %>
<%@ page import = "org.json.simple.JSONObject" %>
<%
request.setCharacterEncoding("utf-8");
//검색값을 받음, 없을떄 초기값 '신사동'
String strDong = request.getParameter("strDong")!=null?request.getParameter("strDong"):"신사";
//DB 처리
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
//json배열 생성
JSONArray jsonArray = new JSONArray();
try{
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
conn = dataSource.getConnection();
String sql = "select * from zipcode where dong like ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "%"+strDong+"%");
rs= pstmt.executeQuery();
int i=1;
while(rs.next()){
JSONObject obj = new JSONObject();
obj.put("recid", i++);
obj.put("seq", rs.getString("seq"));
obj.put("zipcode", rs.getString("zipcode"));
obj.put("sido", rs.getString("sido"));
obj.put("gugun", rs.getString("gugun"));
obj.put("dong", rs.getString("dong"));
obj.put("ri", rs.getString("ri"));
obj.put("bunji", rs.getString("bunji"));
jsonArray.add(obj);
}
}catch(NamingException e){
System.out.println("에러"+e.getMessage());
}catch(SQLException e){
System.out.println("에러"+e.getMessage());
}finally{
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
}
out.println(jsonArray);
%>
ex.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="./css/w2ui-1.4.3.css">
<style>
#wrap { margin: 0 auto; width: 690px; height: 500px;}
</style>
<!-- 그리드는 jQuery 3버전에서 에러남 (현재2016.08.31) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="./js/w2ui-1.4.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =[
//{recid:1, name:"책1", author:"홍길동", publisher:"프리렉", price: 30000, point:10},
];
//그리드
$('#wrap').w2grid({
name: 'grid',
show: {
header: true, //제목보이게
toolbar: true, //툴바 보이게
footer: true,
toolbarColumns: true,
lineNumbers: true
},
//열 정의
columns: [
{field: 'zipcode', caption: '우편번호', size: '10%'},
{field: 'sido', caption: '시도', size: '15%'},
{field: 'gugun', caption: '구군', size: '15%'},
{field: 'dong', caption: '동', size: '15%'},
{field: 'ri', caption: '리', size: '20%'},
{field: 'bunji', caption: '번지', size: '20%'},
],
//데이터
records: data,
//이벤트
onReload: function(target,eventData){ //툴바 새로고침
this.clear();
eventData.preventDefault();
},
onSearch: function(target,event){ //툴바 검색시
//그리드를 함수 안에서 사용가능하도록 변수 선언
var grid =this;
//검색어로 ajax 요청
var strDong = event.searchData[0].value.trim(); //검색어 받음
if(strDong.length<2){
alert('검색어를 2글자 이상 입력하셔야 합니다.');
}else{
$.ajax({
url: './data/json.jsp',
type: 'get',
data: {
strDong: strDong
},
dataType:'json', //데이터를 json으로 받으면 JSON.parse(data) 안써도 됨
success:function(data){
//현재데이터 비우고 받은데이터 채움
grid.clear();
grid.add(data);
//each 함수로 분석하면 엄청 느림 DB에서 recid를 만들어주고 객체를 바로 넣는게 나음
/*
$.each(data,function(key,value){
grid.add({
recid: grid.total +1,
zipcode: value.zipcode,
sido: value.sido,
gugun: value.gugun,
dong: value.dong,
ri: value.ri,
bunji: value.bunji
});
});
*/
},
error: function(xhr,status,error){
alert('에러: '+status+'\n\n'+error);
}
});
}
event.preventDefault();
}
});
});
</script>
</head>
<body>
<div id="wrap"></div>
</body>
</html>
2.게시판 아코디언, 다이얼로그로 만들기 model2 web2.0 SPA(single page application)
폴더구성
3. context.xml
<?xml version="1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/oracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="project"
password="project"
maxTotal="20"
maxWaitMillis="5000" />
</Context>
BoardTO.java
package model1;
// 데이터용 클래스 만듦
public class BoardTO {
private String seq;
private String subject;
private String writer;
private String mail;
private String password;
private String content;
private String hit;
private String wip;
private String wdate;
private int wgap;
public String getSeq() {
return seq;
}
public String getSubject() {
return subject;
}
public String getWriter() {
return writer;
}
public String getMail() {
return mail;
}
public String getPassword() {
return password;
}
public String getContent() {
return content;
}
public String getHit() {
return hit;
}
public String getWip() {
return wip;
}
public String getWdate() {
return wdate;
}
public int getWgap() {
return wgap;
}
public void setSeq(String seq) {
this.seq = seq;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setWriter(String writer) {
this.writer = writer;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setPassword(String password) {
this.password = password;
}
public void setContent(String content) {
this.content = content;
}
public void setHit(String hit) {
this.hit = hit;
}
public void setWip(String wip) {
this.wip = wip;
}
public void setWdate(String wdate) {
this.wdate = wdate;
}
public void setWgap(int wgap) {
this.wgap = wgap;
}
}
BoardDAO.java
package model1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BoardDAO {
private DataSource dataSource;
//생성자에서 tomcat pooling 설정
public BoardDAO() {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
this.dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
} catch (NamingException e) {
System.out.println("에러 : "+ e.getMessage());
}
}
/*각 페이지에 필요한 데이터를 가져오는 메서드를 정의*/
public void boardWrite(){
//필요없음
}
//
public int boardWriteOk(BoardTO to){
Connection conn = null;
PreparedStatement pstmt = null;
int flag = 1;
try{
conn = this.dataSource.getConnection();
String sql = "insert into board1 values (board_seq.nextval, ?, ?, ?, ?, ?, 0, ?, sysdate)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, to.getSubject());
pstmt.setString(2, to.getWriter());
pstmt.setString(3, to.getMail());
pstmt.setString(4, to.getPassword());
pstmt.setString(5, to.getContent());
pstmt.setString(6, to.getWip());
if(pstmt.executeUpdate() ==1){
flag =0;
}
}catch(SQLException e){
System.out.println("에러 : " + e.getMessage());
}finally{
if(pstmt !=null)try{pstmt.close();}catch(SQLException e){};
if(conn !=null)try{conn.close();}catch(SQLException e){};
}
return flag;
}
//
public ArrayList<BoardTO> boardList(){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<BoardTO> result = new ArrayList<>();
try{
conn = dataSource.getConnection();
String sql = "select seq, subject, writer, to_char(wdate,'YY.MM.DD') wdate, hit, trunc(sysdate-wdate) wgap, content from board1 order by seq desc";
pstmt = conn.prepareStatement(sql);
rs= pstmt.executeQuery();
while(rs.next()){
BoardTO to = new BoardTO();
to.setSeq(rs.getString("seq"));
to.setSubject(rs.getString("subject"));
to.setWriter(rs.getString("writer"));
to.setWdate(rs.getString("wdate"));
to.setHit(rs.getString("hit"));
to.setWgap(rs.getInt("wgap"));
to.setContent(rs.getString("content"));
result.add(to);
}
}catch(SQLException e){
System.out.println("에러 : " + e.getMessage());
}finally{
if(rs!=null)try {rs.close();} catch (SQLException e) {}
if(pstmt!=null)try {pstmt.close();} catch (SQLException e) {}
if(conn!=null)try {conn.close();} catch (SQLException e) {}
}
return result;
}
//
public BoardTO boardView(BoardTO to){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
conn = this.dataSource.getConnection();
//조회수 증가
String sql = "update board1 set hit=hit+1 where seq=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, to.getSeq());
pstmt.executeUpdate();
//view창 출력
sql = "select subject, writer, mail, wip, wdate, hit, content from board1 where seq=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, to.getSeq());
rs = pstmt.executeQuery();
if(rs.next()){
to.setSubject(rs.getString("subject"));
to.setWriter(rs.getString("writer"));
to.setMail(rs.getString("mail")==null?"":rs.getString("mail"));
to.setWip(rs.getString("wip"));
to.setWdate(rs.getString("wdate"));
to.setHit(rs.getString("hit"));
to.setContent(rs.getString("content")==null?"":rs.getString("content").replaceAll("\n", "<br>")); //엔터키 처리
}
}catch(SQLException e){
System.out.println("에러 : " + e.getMessage());
}finally{
if(rs!=null)try {rs.close();} catch (SQLException e) {}
if(pstmt!=null)try {pstmt.close();} catch (SQLException e) {}
if(conn!=null)try {conn.close();} catch (SQLException e) {}
}
return to;
}
//
//
public int boardModifyOk(BoardTO to){
Connection conn = null;
PreparedStatement pstmt = null;
int flag = 2;
try{
conn = this.dataSource.getConnection();
String sql = "update board1 set subject=?, mail=?, content=? where seq=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, to.getSubject());
pstmt.setString(2, to.getMail());
pstmt.setString(3, to.getContent());
pstmt.setString(4, to.getSeq());
pstmt.setString(5, to.getPassword());
int result = pstmt.executeUpdate();
if(result ==0){
flag =1;
}else if(result ==1){
flag =0;
}
}catch(SQLException e){
System.out.println("에러 : " + e.getMessage());
}finally{
if(pstmt !=null)try{pstmt.close();}catch(SQLException e){};
if(conn !=null)try{conn.close();}catch(SQLException e){};
}
return flag;
}
//
//
public int boardDeleteOk(BoardTO to){
Connection conn = null;
PreparedStatement pstmt = null;
int flag = 2;
try{
conn = this.dataSource.getConnection();
//delete 처리
String sql = "delete from board1 where seq=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, to.getSeq());
pstmt.setString(2, to.getPassword());
int result = pstmt.executeUpdate();
if(result ==0){
flag =1;
}else if(result ==1){
flag =0;
}
}catch(SQLException e){
System.out.println("에러 : " + e.getMessage());
}finally{
if(pstmt!=null)try {pstmt.close();} catch (SQLException e) {}
if(conn!=null)try {conn.close();} catch (SQLException e) {}
}
return flag;
}
}
4.
Action.java 인터페이스
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response);
}
WriteOkAction.java
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
//MVC model에서 모든데이터 처리하고 view에 필요한 최소한의 데이터를 넘김
public class WriteOkAction implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//데이터 클래스를 생성, 클라이언트 정보 넣음
BoardTO to = new BoardTO();
to.setSubject(request.getParameter("subject"));
to.setWriter(request.getParameter("writer"));
to.setMail(request.getParameter("mail"));
to.setPassword(request.getParameter("password"));
to.setContent(request.getParameter("content"));
to.setWip(request.getRemoteAddr());
//DAO클래스에서 DB데이터를 처리해서 리턴
BoardDAO dao = new BoardDAO();
int flag = dao.boardWriteOk(to);
//데이터 넘김
request.setAttribute("flag", flag);
}
}
ListAction.java
package model2;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
//MVC model에서 모든데이터 처리하고 view에 필요한 최소한의 데이터를 넘김
public class ListAction implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//DAO클래스에서 list에서 필요한 DB데이터를 처리해서 ArrayList로 리턴
BoardDAO dao = new BoardDAO();
ArrayList<BoardTO> lists = dao.boardList();
//데이터 넘김
request.setAttribute("lists", lists);
}
}
/ViewAction.java
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
//MVC model에서 모든데이터 처리하고 view에 필요한 최소한의 데이터를 넘김
public class ViewAction implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//선택글 번호 받아서 TO에 넣음
BoardTO to = new BoardTO();
to.setSeq(request.getParameter("seq"));
//DAO View에서 필요한 DB데이터를 처리해서 리턴
BoardDAO dao = new BoardDAO();
to = dao.boardView(to);
//데이터 넘김
request.setAttribute("to", to);
}
}
ModifyOkAction.java
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
//MVC model에서 모든데이터 처리하고 view에 필요한 최소한의 데이터를 넘김
public class ModifyOkAction implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//데이터 클래스를 생성, 클라이언트 정보 넣음
BoardTO to = new BoardTO();
to.setSeq(request.getParameter("seq"));
to.setSubject(request.getParameter("subject"));
to.setMail(request.getParameter("mail"));
to.setPassword(request.getParameter("password"));
to.setContent(request.getParameter("content"));
//DAO클래스에서 modify_ok에서 필요한 DB데이터를 처리해서 리턴
BoardDAO dao = new BoardDAO();
int flag = dao.boardModifyOk(to);
//데이터 넘김
request.setAttribute("flag", flag);
}
}
DeleteOkAction.java
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
//MVC model에서 모든데이터 처리하고 view에 필요한 최소한의 데이터를 넘김
public class DeleteOkAction implements Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
//데이터 클래스를 생성, 클라이언트 정보 넣기
BoardTO to = new BoardTO();
to.setSeq(request.getParameter("seq"));
to.setPassword(request.getParameter("password"));
//DAO클래스에서 delete_ok에서 필요한 DB데이터를 처리해서 리턴
BoardDAO dao = new BoardDAO();
int flag = dao.boardDeleteOk(to);
//데이터 넘김
request.setAttribute("flag", flag);
}
}
5.controller.java
package servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.RequestDispatcher;
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 model2.Action;
import model2.DeleteOkAction;
import model2.ListAction;
import model2.ModifyOkAction;
import model2.ViewAction;
import model2.WriteOkAction;
/**
* Servlet implementation class BoardController
*/
@WebServlet("*.do")
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("utf-8");
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "";
Action action = null;
//가상의 URL주소가 요청되면 Action처리후, 접속할 실제 폴더 위치 정함
if(path.equals("/*.do") || path.equals("/list.do")){
action = new ListAction();
action.execute(request, response);
url="/WEB-INF/json/board_list1.jsp";
}else if(path.equals("/view.do")){
action = new ViewAction();
action.execute(request, response);
url="/WEB-INF/json/board_view1.jsp";
}else if(path.equals("/write_ok.do")){
action = new WriteOkAction();
action.execute(request, response);
url="/WEB-INF/json/board_write1_ok.jsp";
}else if(path.equals("/modify_ok.do")){
action = new ModifyOkAction();
action.execute(request, response);
url="/WEB-INF/json/board_modify1_ok.jsp";
}else if(path.equals("/delete_ok.do")){
action = new DeleteOkAction();
action.execute(request, response);
url="/WEB-INF/json/board_delete1_ok.jsp";
}
//실제 URL주소 내용을 가상 URL에 띄움
if(!url.equals("")){
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} catch (UnsupportedEncodingException e) {
System.out.println("에러 : " +e.getMessage());
} catch (ServletException e) {
System.out.println("에러 : " +e.getMessage());
} catch (IOException e) {
System.out.println("에러 : " +e.getMessage());
}
}
}
6
board_delete1_ok.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import = "org.json.simple.JSONObject" %>
<%
//디자인에 필요한 최소한의 데이터를 받음
int flag = (Integer)request.getAttribute("flag");
//JSON 변환
JSONObject obj = new JSONObject();
obj.put("flag",flag);
out.println(obj);
%>
board_list1.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@page import="model1.BoardTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page import = "org.json.simple.JSONArray" %>
<%@ page import = "org.json.simple.JSONObject" %>
<%
//ListAction이 보낸 데이터 받음
ArrayList<BoardTO> lists = (ArrayList)request.getAttribute("lists");
JSONArray jsonArray = new JSONArray();
//ArrayList 데이터 json에 담음
StringBuffer result = new StringBuffer();
for(BoardTO to: lists){
JSONObject obj = new JSONObject();
obj.put("seq",to.getSeq());
obj.put("subject",to.getSubject());
obj.put("writer",to.getWriter());
obj.put("wdate",to.getWdate());
obj.put("mail",to.getMail());
obj.put("hit",to.getHit());
obj.put("wgap",to.getWgap());
obj.put("content",to.getContent());
jsonArray.add(obj);
}
out.println(jsonArray);
%>
board_modify1_ok.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import = "org.json.simple.JSONObject" %>
<%
//디자인에 필요한 최소한의 데이터를 받음
int flag = (Integer)request.getAttribute("flag");
//JSON 변환
JSONObject obj = new JSONObject();
obj.put("flag",flag);
out.println(obj);
%>
board_view1.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@page import="model1.BoardTO"%>
<%@ page import = "org.json.simple.JSONObject" %>
<%
//Action에서 디자인에 필요한 최소한의 데이터 받음
BoardTO to = (BoardTO)request.getAttribute("to");
//JSON 변환
JSONObject obj = new JSONObject();
obj.put("seq",to.getSeq());
obj.put("subject",to.getSubject());
obj.put("writer",to.getWriter());
obj.put("mail",to.getMail());
obj.put("wip",to.getWip());
obj.put("wdate",to.getWdate());
obj.put("hit",to.getHit());
obj.put("content",to.getContent());
out.println(obj);
%>
board_write1_ok.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import = "org.json.simple.JSONObject" %>
<%
//디자인에 필요한 최소한의 데이터를 받음
int flag = (Integer)request.getAttribute("flag");
//JSON 변환
JSONObject obj = new JSONObject();
obj.put("flag",flag);
out.println(obj);
%>
7
board2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="./css/base/jquery-ui.css" />
<style type="text/css">
body {font-size : 80%;}
#accordion-resizer{
margin: 0 60px;
max-width: 1500;
}
#btngroup1{
text-align:right;
}
label.header {
font-size: 10pt;
margin-right: 5px;
}
input.text {
width: 80%;
margin-bottom: 12px;
padding: .4em;
}
fieldset {
margin-left: 15px;
margin-top: 15px;
border: 0;
}
</style>
<script type="text/javascript" src="./js/jquery-3.1.0.js"></script>
<script type="text/javascript" src="./js/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* 어코디언 UI 적용 */
$('#accordion').accordion({
heightStyle: 'content'
});
/* write, delete 다이얼로그 처음에 안보이게 */
$('#writeDialog').css('display','none');
$('#deleteDialog').css('display','none');
/* list 서버요청 */
var readServer = function(){
//a.jax 요청 json 데이터 받음
$.ajax({
url: './list.do',
type: 'post',
dataType: 'json',
success: function(json){
//데이터 태그 추가
$('#accordion').empty();
$.each(json, function(index, value){
var title = $('<h3>').html(value.seq+' '+value.subject);
var subject = $('<div>').html('<div style="width: 80%; float: left;">' + value.content + '</div>' + '<div style="text-align:right; vertical-align:bottom;"><button idx="' + value.seq + '" action="modify" class="action">수정</button><button idx="' + value.seq + '" action="delete" class="action">삭제</button></div>');
$('#accordion').append(title);
$('#accordion').append(subject);
});
//어코디언 새로고침
$('#accordion').accordion('refresh');
//수정, 삭제 버튼 새로고침
$('[action="modify"]').button().on('click',modifyfunc);
$('[action="delete"]').button().on('click',deletefunc);
},
error: function(xhr, status, error){
alert('에러 : ' +status+'\n\n'+error);
}
});
};
readServer();
/* write 함수 */
var writefunc = function(){
$('#writeDialog').dialog({
title: '글쓰기',
height: 500,
width: 700,
modal: true,
buttons: {
"글쓰기" : function(){
writeServer();
},
"취소" : function(){
$(this).dialog('close');
}
}
});
}
/* write 서버요청 */
var writeServer = function(){
$.ajax({
url: './write_ok.do',
type: 'post',
data: {
subject: $('#w_subject').val(),
writer: $('#w_writer').val(),
mail: $('#w_mail').val(),
password: $('#w_password').val(),
content: $('#w_content').val()
},
dataType: 'json',
success: function(json){
if(json.flag==0){
alert('글쓰기 성공');
$('#writeDialog').dialog('close');
readServer(); //리스트 새로고침
}else{
alert('글쓰기 실패');
}
},
error: function(xhr, status, error){
alert('에러 : ' +status+'\n\n'+error);
}
});
};
/* modify 함수 */
var modifyfunc = function(){
//클릭한 버튼의 seq 가져옴
var seq = $(this).attr('idx');
//seq와 일치하는 데이터 가져와서 수정창에 뿌리기
$.ajax({
url: './view.do',
type: 'post',
data: {seq: seq},
dataType: 'json',
success: function(json){
$('#w_subject').val(json.subject);
$('#w_writer').val(json.writer);
$('#w_mail').val(json.mail);
$('#w_content').val(json.content);
},
error: function(xhr, status, error){
alert('에러 : ' +status+'\n\n'+error);
}
});
//수정창 띄우기
$('#writeDialog').dialog({ //write 다이얼로그태그 재사용
title: '글수정',
height: 500,
width: 700,
modal: true,
buttons: {
"글수정" : function(){
modifyServer(seq); //seq를 매개변수로 넘겨줌
},
"취소" : function(){
$(this).dialog('close');
}
}
});
}
/* modify 서버 요청 */
var modifyServer = function(seq){
$.ajax({
url: './modify_ok.do',
type: 'post',
data: {
seq: seq,
subject: $('#w_subject').val(),
writer: $('#w_writer').val(),
mail: $('#w_mail').val(),
password: $('#w_password').val(),
content: $('#w_content').val()
},
dataType: 'json',
success: function(json){
if(json.flag==0){
alert('수정 성공');
$('#writeDialog').dialog('close');
readServer(); //리스트 새로고침
}else{
alert('수정 실패');
}
},
error: function(xhr, status, error){
alert('에러 : ' +status+'\n\n'+error);
}
});
};
/* delete 함수 */
var deletefunc = function(){
//클릭한 버튼의 seq 가져오기
var seq = $(this).attr('idx');
$('#deleteDialog').dialog({
height: 200,
width: 300,
modal: true,
buttons: {
"글삭제" : function(){
deleteServer(seq); //seq를 매개변수로 넘겨줌
},
"취소" : function(){
$(this).dialog('close');
}
}
});
}
/* delete 서버 요청 */
var deleteServer = function(seq){
$.ajax({
url: './delete_ok.do',
type: 'post',
data: {
seq: seq,
password: $('#d_password').val()
},
dataType: 'json',
success: function(json){
if(json.flag==0){
alert('삭제 성공');
$('#deleteDialog').dialog('close');
readServer(); //리스트 새로고침
}else{
alert('삭제 실패');
}
},
error: function(xhr, status, error){
alert('에러 : ' +status+'\n\n'+error);
}
});
};
/* write 버튼 */
$('button[action="write"]').button().on('click',writefunc);
});
</script>
</head>
<body>
<div id="accordion-resizer">
<div id="btngroup1">
<button action="write" class="action">글쓰기</button>
</div>
<br><hr /><br />
<div id="accordion"></div>
<div id="writeDialog" title="글쓰기">
<fieldset>
<div>
<label for="subject" class="header">제 목</label>
<input type="text" id="w_subject" class="text ui-widget-content ui-corner-all"/>
</div>
<div>
<label for="writer" class="header">이 름</label>
<input type="text" id="w_writer" class="text ui-widget-content ui-corner-all"/>
</div>
<div>
<label for="mail" class="header">메 일</label>
<input type="text" id="w_mail" class="text ui-widget-content ui-corner-all"/>
</div>
<div>
<label for="password" class="header">비밀 번호</label>
<input type="password" id="w_password" class="text ui-widget-content ui-corner-all"/>
</div>
<div>
<label for="content" class="header">본 문</label>
<br />
<textarea rows="15" cols="100" id="w_content" class="text ui-widget-content ui-corner-all"> </textarea>
</div>
</fieldset>
</div>
<div id="deleteDialog" title="글삭제">
<fieldset>
<div>
<label for="password" class="header">비밀 번호</label>
<input type="password" id="d_password" class="text ui-widget-content ui-corner-all"/>
</div>
</fieldset>
</div>
</div>
</body>
</html>
댓글 없음:
댓글 쓰기