관리 메뉴

거니의 velog

230925_AJAX 강의 본문

대덕인재개발원/대덕인재개발원_Front End

230925_AJAX 강의

Unlimited00 2023. 9. 25. 11:11

[IMemberService.java]

package kr.or.ddit.member.service;

import java.util.List;
import java.util.Map;

import kr.or.ddit.member.vo.MemberVO;

public interface IMemberService {

	// 추상 메서드 선언
	
	// 전체 리스트 가져오기
	public List<MemberVO> selectMember();
	
	// id, pass 검색 데이터 가져오기
	public MemberVO searchByIdPass(Map<String, Object> map);
	
}

[IMemberDAO.java]

package kr.or.ddit.member.dao;

import java.util.List;
import java.util.Map;

import kr.or.ddit.member.vo.MemberVO;

public interface IMemberDAO {

	// 추상 메서드 선언
	
	// 전체 리스트 가져오기
	public List<MemberVO> selectMember();
	
	// id, pass 검색 데이터 가져오기
	public MemberVO searchByIdPass(Map<String, Object> map);
	
}

[MemberDaoImpl.java]

package kr.or.ddit.member.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import kr.or.ddit.member.vo.MemberVO;
import kr.or.ddit.mybatis.config.MyBatisUtil;

/*
 * Data Access Object
 * SqlSession객체가 필요.
 * Singleton을 통해 자신의 객체를 생성해서 return하는 메소드 필요(getDaoInstance()).
 */
public class MemberDaoImpl implements IMemberDAO {

	// 싱글톤 패턴
	private static MemberDaoImpl dao;
	private MemberDaoImpl() {}
	public static MemberDaoImpl getInstance() {
		if(dao == null) dao = new MemberDaoImpl();
		return dao;
	}
	
	@Override
	public List<MemberVO> selectMember() {
		SqlSession session = null;
		List<MemberVO> memberList = null;
		
		try {
			session = MyBatisUtil.getSqlSession();
			memberList = session.selectList("member.selectMember");
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return memberList;
	}

	@Override
	public MemberVO searchByIdPass(Map<String, Object> map) {
		SqlSession session = null;
		MemberVO memVo = null;
		
		try {
			session = MyBatisUtil.getSqlSession();
			memVo = session.selectOne("member.searchByIdPass", map);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return memVo;
	}

}

[MemberServiceImpl.java]

package kr.or.ddit.member.service;

import java.util.List;
import java.util.Map;

import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.member.vo.MemberVO;

/*
 * DAO 객체가 필요
 * 싱글톤을 위한 자기 자신의 객체를 생성해서 리턴하는 메소드
 */
public class MemberServiceImpl implements IMemberService {

	private IMemberDAO dao;
	
	// 싱글톤 패턴
	private static MemberServiceImpl service;
	private MemberServiceImpl() {
		dao = MemberDaoImpl.getInstance();
	}
	public static MemberServiceImpl getInstance() {
		if(service == null) service = new MemberServiceImpl();
		return service;
	}
	
	@Override
	public List<MemberVO> selectMember() {
		return dao.selectMember();
	}

	@Override
	public MemberVO searchByIdPass(Map<String, Object> map) {
		return dao.searchByIdPass(map);
	}

}

[memberController.jsp]

<%@page import="kr.or.ddit.member.vo.MemberVO"%>
<%@page import="java.util.List"%>
<%@page import="kr.or.ddit.member.service.IMemberService"%>
<%@page import="kr.or.ddit.member.service.MemberServiceImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	// 클라이언트 요청시 전송 데이터 받기
	
	// Service객체 얻기
	IMemberService service = MemberServiceImpl.getInstance();

	// service메서드 호출 - 결과값 얻기 - List
	List<MemberVO> memList = service.selectMember();
	
	// List 결과로 json 객체 배열 형태의 응답 결과를 생성한다.
	// view 페이지로 이동 - viewSelect.jsp - list 결과를 가지고 
	// Controller와 view 페이지가 list 결과를 공유 해야 한다.
	// request와 reponse객체가 공유되는 forward방식
	
	// forward - controller와 view 페이지 사이에
	// 			 request와 response가 공유
	// controller -> request.getAttribute(key, value);
	// RequestDispatcher -> disp.forward(request, response);
	// redirect - 공유 하지 못함
	
	request.setAttribute("listResult", memList);
	RequestDispatcher disp = request.getRequestDispatcher("viewSelect.jsp");
	
	disp.forward(request, response);
%>

[viewSelect.jsp]

<%@page import="kr.or.ddit.member.vo.MemberVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	// 컨트롤러에서 저장한 결과를 꺼내기
	List<MemberVO> list = (List<MemberVO>) request.getAttribute("listResult");

	// json 형식의 객체 배열을 생성한다.
%>
[
	<% 
		for(int i=0; i<list.size(); i++) {
			MemberVO vo = list.get(i);
			if(i > 0) out.print(",");
	%>
	
		{
			"id" : "<%= vo.getMem_id() %>",
			"name" : "<%= vo.getMem_name() %>",
			"hp" : "<%= vo.getMem_hp() %>",
			"addr" : "<%= vo.getMem_add1() + " " + vo.getMem_add2()  %>"
		}
	
	<%		
		}
	%>
]

[ajaxTest03.html]

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax03" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax03" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax03</title>
        <link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
        <style>
            div, form {
                border: 3px dotted yellowgreen;
                margin: 20px;
                padding: 20px;
                font-size: 1.2rem;
                word-break: break-all;
            }
            input[type=button],
            button[type=button] {
                display: inline-block;
                padding: 5px 10px;
                text-align: center;
                font-size: 1.2em;
                font-weight: 700;
                background-color: blue;
                color: white;
                border: none;
                border-radius: 4px;
                margin-right: 10px;
                cursor: pointer;
            }
        </style>
        <script>
            
            $(function(){
                
                $("#btn1").click(function(){
                    $.ajax({
                        url : "memberController.jsp",
                        type : "get",
                        success : function(res){
                            var code = `<table>`;
                            code += `<tr><th>아이디</th>`;
                            code += `<th>이름</th>`;
                            code += `<th>전화번호</th>`;
                            code += `<th>주소</th></tr>`;
                            
                            $.each(res, function(i, v){
                            	code += `<tr><td>${v.id}</td>`;
                                code += `<td>${v.name}</td>`;
                                code += `<td>${v.hp}</td>`;
                                code += `<td>${v.addr}</td></tr>`;
                            });
                            
                            code += `</table>`;
                            
                            $("#result1").append(code);
                        },
                        error : function(xhr){
                            alert("상태 : " + xhr.status);
                        },
                        dataType : 'json'
                    });
                });
                
            });
            
        </script>
    </head>
    <body>

        <hr color="red" /> 
        
        <h1>
            Ajax03 실습 1-1
            <br />
            memberSingleton.html
            <br />
            전체 데이터 가져오기
        </h1>
        
        <br />
        <input id="btn1" type="button" value="실행" />
        <br />
        
        <div id="result1"></div>
        
        <hr color="red" />
        
        <h1>
            Ajax03 실습 2-1
            <br />
            memberSingleton.html
            <br />
            입력 데이터 가져오기
        </h1>
        
        <br />
        <input id="btn2" type="button" value="실행" />
        <br />
        
        <div id="result2"></div>
        
        <hr color="red" />
   
    </body>
</html>


[SelectByIdPass.java]

package kr.or.ddit.member.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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 kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;


@WebServlet("/SelectByIdPass.do")
public class SelectByIdPass extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
		System.out.println("init() 메서드 호출...");
	}

	public void destroy() {
		System.out.println("destroy() 메서드 호출...");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		// 클라이언트 요청시 전송 데이터 받기
		String userId = request.getParameter("id");
		String userPass = request.getParameter("pass");
		
		// service 객체 얻기
		IMemberService service = MemberServiceImpl.getInstance();
		
		// service 메소드 호출하기 - 결과값 받기 - MemberVO
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", userId);
		map.put("pass", userPass);
		
		MemberVO vo = service.searchByIdPass(map);
		
		// 결과값을 view 페이지로 이동하기 위해서 저장
		request.setAttribute("resultVo", vo);
		
		// forward를 위한 객체 생성
		RequestDispatcher disp = request.getRequestDispatcher("/0925/viewSelectOne.jsp");
		
		// forward실행
		disp.forward(request, response);
		
	}

}

[viewSelectOne.jsp]

<%@page import="kr.or.ddit.member.vo.MemberVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	// 서블릿에서 저장한 결과 데이터 꺼내기
	MemberVO vo = (MemberVO) request.getAttribute("resultVo");
	// 결과 json object 데이터 생성
	if(vo != null){
%>
	{
		"resp" : "ok",
		"id" : "<%= vo.getMem_id() %>",
		"name" : "<%= vo.getMem_name() %>",
		"hp" : "<%= vo.getMem_hp() %>",
		"mail" : "<%= vo.getMem_mail() %>",
		"addr" : "<%= vo.getMem_add1() + " " + vo.getMem_add2() %>"
	}
<%
	}else{
%>
	{
		"resp" : "no"
	}
<%
	}
%>

[ajaxTest03.html]

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax03" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax03" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax03</title>
        <link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
        <style>
            div, form {
                border: 3px dotted yellowgreen;
                margin: 20px;
                padding: 20px;
                font-size: 1.2rem;
                word-break: break-all;
            }
            input[type=button],
            button[type=button] {
                display: inline-block;
                padding: 5px 10px;
                text-align: center;
                font-size: 1.2em;
                font-weight: 700;
                background-color: blue;
                color: white;
                border: none;
                border-radius: 4px;
                margin-right: 10px;
                cursor: pointer;
            }
            table {
                border-collapse: collapse;
                border: 2px solid blue;
            }
            table th {
                background-color: blue;
                color: white;
                width: calc(100% / 4);
                height: 50px;
            }
            table td {
                height: 50px;
            }
        </style>
        <script>
            
            $(function(){
                
                $("#btn1").click(function(){
                    $.ajax({
                        url : "memberController.jsp",
                        type : "get",
                        success : function(res){
                            var code = `<table border='1'>`;
                            code += `<tr><th>아이디</th>`;
                            code += `<th>이름</th>`;
                            code += `<th>전화번호</th>`;
                            code += `<th>주소</th></tr>`;
                            
                            $.each(res, function(i, v){
                            	code += `<tr><td>${v.id}</td>`;
                                code += `<td>${v.name}</td>`;
                                code += `<td>${v.hp}</td>`;
                                code += `<td>${v.addr}</td></tr>`;
                            });
                            
                            code += `</table>`;
                            
                            $("#result1").append(code);
                        },
                        error : function(xhr){
                            alert("상태 : " + xhr.status);
                        },
                        dataType : 'json'
                    });
                }); // btn1
                
                $("#btn2").click(function(){
                	// 입력한 값 가져오기
                	var id = $("#id").val().trim();
                	if(id.length < 1) {
                		alert("아이디를 입력하세요...");
                		return false;
                	}
                	// 입력 여부 확인
                	var pass = $("#pass").val().trim();
                	if(pass.length < 1) {
                		alert("비밀번호를 입력하세요...");
                		return false;
                	}
                	
                	// 모두 입력되었으면 서버로 보내기
                	$.ajax({
                		url : '/jqpro/SelectByIdPass.do',
                		type : 'post',
                		data : {"id" : id, "pass" : pass},
                		success : function(res){
                			
                			if(res.resp == "ok"){
	                			var code = `<table border='1'>`;
	                            code += `<tr><th>아이디</th>`;
	                            code += `<th>이름</th>`;
	                            code += `<th>전화번호</th>`;
	                            code += `<th>주소</th></tr>`;
	                            
	                           	code += `<tr><td>${res.id}</td>`;
	                            code += `<td>${res.name}</td>`;
	                            code += `<td>${res.hp}</td>`;
	                            code += `<td>${res.addr}</td></tr>`;
	                            
	                            code += `</table>`;
                			}else {
                				alert("일치하는 데이타는 없습니다.");
                				return false;
                			}
                            
                            $("#result2").append(code);
                		},
                		error : function(xhr, status, error){
                			alert("상태 : " + xhr.status + "\n" + xhr.statusText);
                		},
                		dataType : 'json'
                	});
                }); // btn2
                
            }); // document
            
        </script>
    </head>
    <body>

        <hr color="red" /> 
        
        <h1>
            Ajax03 실습 1-1
            <br />
            memberSingleton.html
            <br />
            전체 데이터 가져오기
        </h1>
        
        <br />
        <input id="btn1" type="button" value="실행" />
        <br />
        
        <div id="result1"></div>
        
        <hr color="red" />
        
        <h1>
            Ajax03 실습 2-1
            <br />
            memberSingleton.html
            <br />
            입력 데이터 가져오기
        </h1>
        
        <form>
        	<input id="id" type="text" placeholder="아이디 입력" /><br />
        	<input id="pass" type="password" placeholder="비밀번호 입력" /><br />
	        <input id="btn2" type="button" value="실행" />
        </form>
        
        <div id="result2"></div>
        
        <hr color="red" />
   
    </body>
</html>

'대덕인재개발원 > 대덕인재개발원_Front End' 카테고리의 다른 글

230927_AJAX 강의  (0) 2023.09.27
230926_AJAX 강의  (0) 2023.09.26
230922_AJAX 강의  (0) 2023.09.22
230921_AJAX 강의  (0) 2023.09.21
230920_AJAX 강의  (0) 2023.09.20