본문 바로가기
학습/JSP

32. Ajax CRUD(로그인 중복 체크(간단) / json 연습)

by Elfen Lied 2022. 12. 13.
반응형

 

- webapp / test03 / ajax1.jsp 생성

 

- ajax1.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>
</head>
<body>
<p>hello?</p>
<p>안녕?</p>
</body>
<script>
	let person1 = {
		age : "10",
		name : "홍길동",
		greeting : function hello() {
			alert('헤이');
		}
	};
	console.log(person1.name);
	console.log(person1['age']);
	
	person1.hello();
</script>
</html>

 

 

객체 안에 함수를 부를때 person1.hello() 요청하면 찾을수 없고

person1.greeting() 프로퍼티로 요청해야 됨

 

- person1.hello()로 요청시

 

- person1.greeting()로 요청시

함수가 실행된다.

 

위에 개념 실습 끝나면 제이쿼리 링크를 준비한다

 

 


- pom.xml

<dependencies>
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.4</version>
		</dependency>

		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-dbcp</artifactId>
			<version>10.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.24</version>
			<scope>provided</scope>
		</dependency>
</dependencies>

 

 

- 아이디 중복 검사

 

- webapp / test03 / ajax1.jsp 생성

 

- ajax1.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>

<button>전송</button>

<p>hello?</p>
<p>안녕?</p>

<div class="message"></div>

</body>

<script>
$(function() {
	$('button').on('click', function() {
		$.ajax({
			type : 'get', // 전송방식
			dataType : 'text', // 데이터 타입
			url : '/pro16_/ajaxtest1', // 전송url
			data : { userName : '홍길동' },
			success : function(result) { // 요청 및 응답 성공
				$('.message').append(result + "<br>")
			},
			error : function() { // 요청 및 응답 실패		
				alert('실패')
			},
			complete : function() {
				alert('정확히 입력 해주세요');
			}
		}); // ajax end
	}); // on end
}); // document ready end

</script>
</html>

 

 

 

- sec01.ex01 패키지 AjaxTest1 서블릿 생성

 

AjaxTest1 

package sec01.ex01;

import java.io.IOException;
import java.io.PrintWriter;

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("/ajaxtest1")
public class AjaxTest1 extends HttpServlet {
	
    public AjaxTest1() {
        super();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet실행");
		doHandle(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doPost실행");
		doHandle(request, response);
	}
	
	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		String userName = request.getParameter("userName");
		System.out.println("이름 : " + userName);
	
		out.print("하이 " + userName);
	}

}

 

 

 

- sec02.ex01 패키지 MemberDao 클래스 생성

 

- MemberDao 

package sec02.ex01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class MemberDao {
	private DataSource dataSource;
	
	public MemberDao() {
		try {
			Context ctx = new InitialContext();
			Context ctxEnv = (Context) ctx.lookup("java:/comp/env");
			dataSource = (DataSource) ctxEnv.lookup("jdbc/oracle");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public boolean overlapedId(String id) {
		boolean result = false;
		String query = "SELECT DECODE(COUNT(*),1,'TRUE','FALSE') AS result FROM t_member WHERE id=?";
		try (
			Connection conn = dataSource.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
		){
			pstmt.setString(1, id);
			try(ResultSet rs = pstmt.executeQuery();) {
				if(rs.next()) {
					result = Boolean.parseBoolean(rs.getString("result"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
}

 

 

 

- webapp / test03 / ajax2.jsp 생성

 

- ajax2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>아이디 중복 체크</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<form action="test.jsp">

	아이디 : <input type="text" class="userId" name="id">
	
	<button type="button" class="idCheck">아이디 중복체크</button>
	<div class="message"></div><br>
	
	이메일 : <input type="text" class="email">
	<button type="button" class="join" >회원가입</button>

</form>
</body>

<script>
$(function() {
	let idChecked = false;
	$('.idCheck').on('click', function() {
		let userId = $('.userId').val();
		$.ajax({
			type : 'post',
			url : '/pro16_/member',
			data : { 'userId' : userId },
			success : function(result) {
				console.log(result);				
				if(result.isAvailable) {
					$('.message').html("사용 가능한 ID입니다")
					idChecked = true;	
				} else {
					$('.message').html("중복된 ID입니다")
					idChecked = false;	
				}
				
			},
			error : function() {
				alert('에러')
			}
		}); // ajax end
	}); // on end
	
	$('.join').on('click', function() {
		if(idChecked) {
			$('form').submit();
		} else {
			alert('아이디 중복 체크 하세요')			
		}
	});
	
}); // document ready end

</script>
</html>

 

 

 

- sec02.ex01 패키지 MemberServlet 서블릿생성

 

- MemberServlet

package sec02.ex01;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONObject;

@WebServlet("/member")
public class MemberServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}
	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String userId = request.getParameter("userId");
		MemberDao dao = new MemberDao();
		JSONObject idCheck = new JSONObject();
		
		boolean result = dao.overlapedId(userId);
		if(result) { // 중복된 아이디
			idCheck.put("isAvailable", false);
			out.print(idCheck);
		} else { // 사용 가능한 아이디
			idCheck.put("isAvailable", true);
			out.print(idCheck);
		}
	}

}

 

- 실행

중복일 경우

 

중복이 아닐 경우

 


- json 연습

 

- webapp / test04 / json1.jsp 생성

 

-  json1.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<button id="checkJson">출력</button>
<div class="output"></div>
</body>

<script>
$(function() {
	
	$('#checkJson').on('click', function(){
		let jsonStr = '{ "name" : ["홍길동", "이순신", "임꺽정"] }'; // 문자열
		let jsonInfo = JSON.parse(jsonStr); // 문자열을 자바스크립트 객체로 변환
		console.log(jsonInfo); // 결과 확인
		console.log(jsonInfo.name); // name속성에 해당하는 배열
		console.log(jsonInfo.name[0]); // 홍길동
		console.log(jsonInfo.name[1]); // 이순신
		console.log(jsonInfo.name[2]); // 임꺽정
		
		let output = "회원이름<br>";
		output += "==================================<br>";
		for(let n of jsonInfo.name) {
			output += n + "<br>";
		}
		$('.output').html(output);
	}); // on end
	
}); // end
</script>

</html>

 

 

- json2.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<button id="checkJson">출력</button>
<div class="output"></div>
</body>

<script>
$(function() {
	
	$('#checkJson').on('click', function(){
		let jsonStr = '{ "age":[22,33,44], "name":["홍길동","이순신","임꺽정"] }';
		let jsonInfo = JSON.parse(jsonStr);

		let output = "회원나이<br>";
		output += "==============================<br>";
		for(let age of jsonInfo.age) {
			output += age + "<br>";
		}
		$('.output').html(output);		
	}); // on end
	
}); // end
</script>

</html>

 

 

- json3.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<button id="checkJson">출력</button>
<div class="output"></div>
</body>

<script>
$(function() {
	
	$('#checkJson').on('click', function(){
		let jsonStr = '{ "name":"박지성", "age":25, "gender":"남자", "nickname":"두개의 심장" }';
		let jsonInfo = JSON.parse(jsonStr);
		
		let output = "회원정보<br>";
		output += "이름 : " + jsonInfo.name + "<br>";
		output += "나이 : " + jsonInfo.age + "<br>";
		output += "성별 : " + jsonInfo['gender'] + "<br>";
		output += "별명 : " + jsonInfo['nickname'];
		
		$('.output').html(output);
	}); // on end
	
}); // end
</script>

</html>

 

 

 

자바스크립트 파일 생성

- json4.js

$(function() {
	
	let name = "홍길동";
	let age = 20;
	let gender = "남자";
	
	let info = "이름 : " + name + " 나이 : " + age + " 성별 " + gender;
	let info2 = `이름 : ${name}, 나이 : ${age}, 성별 : ${gender}`;
	console.log(info); 
	console.log(info2); 

	$('#checkJson').on('click', function(){
		let jsonStr = `{
			"members" : [
				{ "name":"박지성", "age":"25", "gender":"남자", "nick":"두개의 심장" },
				{ "name":"안정환", "age":"27", "gender":"남자", "nick":"테리우스" }
			],
			"coach" : [
				{ "name":"히딩크", "age":"50", "gender":"남자", "nick":"히동구" },
				{ "name":"박항서", "age":"41", "gender":"남자", "nick":"베트남국민영웅" }
			]
		}`;
		
		let jsonInfo = JSON.parse(jsonStr);
		let members = "선수 정보<br>";
		members += "=========================<br>";
		
		for(let m of jsonInfo.members) {
			members += `이름 : ${m.name}, 나이 : ${m.age}, 성별 : ${m.gender}, 별명 : ${m.nick} <br>`;
		}
		$('.members').html(members);

		let coach = "코치 정보<br>";
		coach += "=========================<br>";
		
		for(let m of jsonInfo.coach) {
			coach += `이름 : ${m.name}, 나이 : ${m.age}, 성별 : ${m.gender}, 별명 : ${m.nick} <br>`;
		}
		$('.coach').html(coach);
	}); // on end
	
}); // end

 

 

- json4.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="json4.js"></script>

</head>
<body>
<button id="checkJson">출력</button>
<div class="members"></div><br>
<div class="coach"></div>
</body>

<script>

</script>

</html>

 

 

- json5.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

</head>
<body>
<button id="checkJson">출력</button>
<div class="output"></div>
</body>

<script>
$(function() {
	
	let _jsonInfo = '{"name":"박지성", "age":25, "gender":"남자", "nick":"두개의 심장"}';
	
	$('#checkJson').on('click', function(){
			
		$.ajax({
			type : 'post',
			url : '/pro16_/json1',
			data : { jsonInfo : _jsonInfo },
			success : function(result) {
				alert('성공');
				console.log(result);
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end
		
	}); // on end
}); // end
</script>

</html>

 

 

 

- 메이븐 저장소에서 json.simple을 pom.xml에 추가

 

 

 

- sec03.ex01 패키지 JsonServlet1서블릿 생성

 

- JsonServlet1

package sec03.ex01;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

@WebServlet("/json1")
public class JsonServlet1 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String jsonInfo = request.getParameter("jsonInfo");
		System.out.println(jsonInfo);
		
		try {
			JSONParser jsonParser = new JSONParser();
			JSONObject member = (JSONObject) jsonParser.parse(jsonInfo);
			System.out.println("이름 : " + member.get("name"));
			System.out.println("나이 : " + member.get("age"));
			System.out.println("성별 : " + member.get("gender"));
			System.out.println("별명 : " + member.get("nick"));
			out.print("서블릿 응답 : 성공");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	}

}

 


- JsonServlet2 서블릿 생성

 

코드에 노란줄이 나오는데  ctrl + 1 눌러서 @ Add @Suppress.... 선택하면 사라짐

JSONObject가 제네릭타입을 지원하지 않기 때문에 나타남

 

package sec03.ex01;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet("/json2")
public class JsonServlet2 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		try {
			JSONObject member1 = new JSONObject();
			JSONObject member2 = new JSONObject();
			member1.put("name", "박지성");
			member1.put("age", "25");
			member1.put("gender", "남자");
			member1.put("nick", "두개의 심장");

			member2.put("name", "김연아");
			member2.put("age", "20");
			member2.put("gender", "여자");
			member2.put("nick", "피겨여왕");
			
			JSONArray memberArray = new JSONArray();
			memberArray.add(member1);
			memberArray.add(member2);
			
			JSONObject members = new JSONObject();
			members.put("members", memberArray);
		
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

 

 

- json6.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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

</head>
<body>
<button id="checkJson">출력</button>
<div class="output"></div>
</body>

<script>
$(function() {
	
	$('#checkJson').on('click', function(){
			
		$.ajax({
			type : 'post',
			url : '/pro16_/json2',
			success : function(result) {
				let data = JSON.parse(result);
				console.log(data);
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end
		
	}); // on end
}); // end
</script>

</html>

 

 

- sec03.ex01 패키지 JsonServlet3서블릿 생성

 

- JsonServlet3

package sec03.ex01;

import java.io.IOException;
import java.io.PrintWriter;

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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet("/json3")
public class JsonServlet3 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		try {
			JSONObject member1 = new JSONObject();
			JSONObject member2 = new JSONObject();
			member1.put("name", "박지성");
			member1.put("age", "25");
			member1.put("gender", "남자");
			member1.put("nick", "두개의 심장");

			member2.put("name", "김연아");
			member2.put("age", "20");
			member2.put("gender", "여자");
			member2.put("nick", "피겨여왕");
			
			JSONArray memberArray = new JSONArray();
			memberArray.add(member1);
			memberArray.add(member2);
			
			JSONObject members = new JSONObject();
			members.put("members", memberArray);
		
			out.print(members);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

 

response.setContentType("application/json; charset=utf-8");

- text/html : 단순 문자열 응답이고

- application/json : json으로 응답

 

 

 


- 여기서부터 AJAX CRUD 시작

- crud 전체 파일트리

 

 

- sec04.ex01 패키지 BoardServlet 서블릿, BoardDao, BoardVO 클래스 생성

 

- BoardVO

package sec04.ex01;

import java.sql.Date;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class BoardVO {
	private int bno;
	private String title;
	private String content;
	private String writer;
	private Date writeDate;
}

 

 

- BoardDao

package sec04.ex01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.sql.DataSource;

public class BoardDao {
	
	private DataSource dataSource;
	private int bno;
	
	public BoardDao() {
		try {
			Context ctx = new InitialContext();
			Context envCtx = (Context) ctx.lookup("java:/comp/env");
			dataSource = (DataSource) envCtx.lookup("jdbc/oracle");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public List<BoardVO> list() {
		List<BoardVO> list = new ArrayList<BoardVO>();
		String query = "SELECT * FROM board_t ORDER BY bno DESC";
		try (
			Connection conn = dataSource.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
			ResultSet rs = pstmt.executeQuery();
		){
			while (rs.next()) {
				BoardVO vo = BoardVO.builder()
						.bno(rs.getInt("bno"))
						.title(rs.getString("title"))
						.content(rs.getString("content"))
						.writer(rs.getString("writer"))
						.writeDate(rs.getDate("writeDate")).build();
				list.add(vo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public BoardVO detail(int bno) {
		String query = "SELECT * FROM board_t WHERE bno=?";
		BoardVO vo = null;
		try (
			Connection conn = dataSource.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
		){
			pstmt.setInt(1, bno);
			try(ResultSet rs = pstmt.executeQuery();) {
				if(rs.next()) {
				 	vo = BoardVO.builder()
							.bno(rs.getInt("bno"))
							.title(rs.getString("title"))
							.content(rs.getString("content"))
							.writer(rs.getString("writer"))
							.writeDate(rs.getDate("writeDate")).build();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	public void delBoard(int bno) {
		String query = "DELETE FROM board_t WHERE bno=?";
		try (
				Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn.prepareStatement(query);
			){
				pstmt.setInt(1, bno);
				pstmt.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public void addBoard(BoardVO vo) {
		String query = "INSERT INTO board_t(bno, title, content, writer) VALUES(bno_seq.NEXTVAL,?,?,?)";
		try (
			Connection conn = dataSource.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
		){
			pstmt.setString(1, vo.getTitle());
			pstmt.setString(2, vo.getContent());
			pstmt.setString(3, vo.getWriter());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void modBoard(BoardVO vo) {
		String query = "UPDATE board_t SET title=?, content=? WHERE bno=?";
		try (
			Connection conn = dataSource.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(query);
		){
			pstmt.setString(1, vo.getTitle());
			pstmt.setString(2, vo.getContent());
			pstmt.setInt(3, vo.getBno());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

- BoardServlet

package sec04.ex01;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 org.json.simple.JSONObject;

import com.google.gson.Gson;

@WebServlet("/board/*")
public class BoardServlet extends HttpServlet {
	private BoardDao dao;
	
	@Override
	public void init() throws ServletException {
		dao = new BoardDao();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandel(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandel(request, response);
	}
	
	private void doHandel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String pathInfo = request.getPathInfo();
		if(pathInfo == null || pathInfo.equals("/") || pathInfo.equals("/list")) { // 글목록
			List<BoardVO> list = dao.list();
			String boardList = new Gson().toJson(list);
			out.print(boardList);
		} else if(pathInfo.equals("/detail")) { // 글상세
			String paramBno = request.getParameter("bno");
			BoardVO vo = dao.detail(Integer.parseInt(paramBno));
			String detail = new Gson().toJson(vo);
			out.print(detail);
		} else if(pathInfo.equals("/remove")) { // 글삭제
			String paramBno = request.getParameter("bno");
			dao.delBoard(Integer.parseInt(paramBno));
			String result = new Gson().toJson("삭제성공");
			out.print(result);
		} else if(pathInfo.equals("/write")) { // 글쓰기
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			String writer = request.getParameter("writer");
			BoardVO vo = BoardVO.builder()
					.title(title)
					.content(content)
					.writer(writer).build();
			dao.addBoard(vo);
			String result = new Gson().toJson("등록성공");
			out.print(result);
		} else if(pathInfo.equals("/modify")) { // 글수정
			String paramBno = request.getParameter("bno");
			int bno = Integer.parseInt(paramBno);
			BoardVO vo = BoardVO.builder()
					.bno(bno)
					.title(request.getParameter("title"))
					.content(request.getParameter("content")).build();
			dao.modBoard(vo);
			String result = new Gson().toJson("수정성공");
			out.print(result);
		} else {
			throw new ServletException();
		}
	}

}

 

 

- board.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>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="BoardService.js"></script>
<script src="board.js"></script>	
</head>
<body>
<div class="container">
	<div class="my-3">
		<button class="btn btn-primary newBoardBtn" data-toggle="modal">글쓰기</button>
	</div>
	<table class="table board_list">
		<thead>
			<tr>
				<th>번호</th>
				<th>제목</th>
				<th>작성자</th>
				<th>작성일</th>
			</tr>
		</thead>
		<tbody></tbody>
	</table>
	<div class="content"></div>
</div>

<!-- The Modal -->
 <div class="modal" id="write">
   <div class="modal-dialog">
     <div class="modal-content">
     
       <!-- Modal Header -->
       <div class="modal-header">
         <h4 class="modal-title">글쓰기</h4>
         <button type="button" class="close" data-dismiss="modal">&times;</button>
       </div>
       
       <!-- Modal body -->
       <div class="modal-body">
			제목 : <input type="text" class="form-control board_title">
			내용 : <textarea rows="10" class="form-control board_content"></textarea>
			작성자 : <input type="text" class="form-control board_writer">
       		<input type="hidden" class="board_bno">
       </div>
       
       <!-- Modal footer -->
       <div class="modal-footer">
         <button class="btn btn-primary writeBtn">글등록</button>
         <button class="btn btn-primary modBtn">글수정</button>
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
       </div>
       
     </div>
   </div>
 </div>
</body>
</html>

 

 

- board.js

 

게시물 상세 이벤트에서

on메소드에 'click', '.del' 부분에서 클래스 del은 임의로 BoardService.js에 detail함수에 있는 제이쿼리에서

동적으로 태그들을 만들어 주고 있으므로,

만약 선택자로 $('.del').on~ 쓰면 실행이 안된다.

왜냐하면 실행하기 전에는 class에 del을 가진 태그가 존재하지 않기때문이다.

 

따라서, on('click', '.del', function() 으로 작성해서 이벤트를 위임해야함. 

$(function() {
	
	boardService.list(); // 게시물 목록 불러오기
	
	// 게시물 상세 이벤트
	$('.content').on('click', '.del', function() {
		let bnoValue = $(this).data('bno'); // 게시물 번호
		boardService.remove(bnoValue);
	});
	
	// 게시물 등록 이벤트
	$('.writeBtn').on('click', function() {
		let title = $('.board_title').val();
		let content = $('.board_content').val();
		let writer = $('.board_writer').val();

		let boardVO = {
			title : title,
			content : content,
			writer : writer
		}
		boardService.write(boardVO);
		
		$('.board_title, .board_content, .board_writer').val('');
		$('.modal').modal('hide');
	});
	
	// 게시물 수정 처리
	$('.modBtn').on('click', function() {
		let bno = $('.board_bno').val();
		let title = $('.board_title').val();
		let content = $('.board_content').val();
		
		let vo = {
			bno : bno,
			title : title,
			content : content
		}
		boardService.modify(vo);
		
		$('.board_title, .board_content, .board_writer').val('');
		$('.modal').modal('hide');
	});
	
	
	// 게시물 수정 이벤트
	$('.content').on('click', '.mod', function() {
		let bno = $(this).data('bno');
		$.ajax({
			type : 'post',
			url : '/pro16_/board/detail',
			data : {'bno' : bno},
			success : function(vo) {
				$('.board_bno').val(vo.bno);
				$('.modal-title').html('글수정');
				$('.writeBtn').hide();
				$('.modBtn').show();
				$('.board_title').val(vo.title);
				$('.board_content').val(vo.content);
				$('.board_writer').val(vo.writer).prop('readonly', true);
				$('#write').modal('show');
			}
		}); // ajax end
	});
	
	// 새로운 글쓰기 모달창
	$('.newBoardBtn').on('click', function(){
		$('.modal-title').html('글쓰기');
		$('.modBtn').hide();
		$('.writeBtn').show();
		$('.board_writer').prop('readonly', false);
		$('.board_title, .board_content, .board_writer').val('');
		$('#write').modal('show');
	});
		
}); // end

 

 

- BoardService.js 자바스크립트 생성

let boardService = (function() {
	
	function list() {
		console.log('게시물 목록');
		$.ajax({
			type : 'post',
			url : '/pro16_/board/list',
			success : function(list) {
				let output = "";
				for(let b of list) {
					output += `
						<tr>
					        <td>${b.bno}</td>
					        <td><a href="#" onclick="boardService.detail(${b.bno})">${b.title}</a></td>
					        <td>${b.writer}</td>
					        <td>${b.writeDate}</td>
				    	</tr>`;
				}
				$('.board_list tbody').html(output);
				$('.content').html('');
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end
	}
		
	function remove(bnoValue) {
		console.log('게시물 삭제');
		$.ajax({
			type : 'post',
			url : '/pro16_/board/remove',
			data : {bno : bnoValue},
			success : function(result) {
				alert(result);
				boardService.list(); // 게시물 목록 불러오기
			},
			error : function() {
				alert('에러');
			}
		}) ;
	}
	
	function detail(bno) {
		console.log('게시물 상세');
		$.ajax({
			type : 'get',
			url : '/pro16_/board/detail',
			data : {bno : bno},
			success : function(detail) {
					let output = `
							<div class="card">
								<div class="card-header  d-flex justify-content-between">
									<b>${detail.title}</b>
									<div>
										<button class="btn btn-warning mod" data-bno="${detail.bno}">수정</button>
										<button class="btn btn-danger del" data-bno="${detail.bno}">삭제</button>
									</div>
								</div>
								<div class="card-body">${detail.content}</div>
								<div class="card-footer d-flex justify-content-between">
									<span>${detail.writer}</span>
									<span>${detail.writeDate}</span>
								</div>
							</div>`;
					$('.content').html(output);
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end
	}
	
	function write(vo) {
		
		$.ajax({
			type : 'post',
			url : '/pro16_/board/write',
			data : vo,
			success : function(result) {
				alert(result);
				boardService.list();
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end

	}
	
	function modify(vo) {
		
		$.ajax({
			type : 'post',
			url : '/pro16_/board/modify',
			data : vo,
			success : function(result) {
				alert(result);
				boardService.list();
				boardService.detail(vo.bno);
			},
			error : function() {
				alert('에러');
			}
		}); // ajax end
	}
	
	return {
		list : list,
		remove : remove,
		detail : detail,
		write : write,
		modify : modify,
	};
	
})();
반응형

댓글