관리 메뉴

거니의 velog

230926_AJAX 강의 본문

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

230926_AJAX 강의

Unlimited00 2023. 9. 26. 10:39

[BuyerVO.java]

package kr.or.ddit.buyer.vo;

public class BuyerVO {

	private String buyer_id;
	private String buyer_name;
	private String buyer_lgu;
	private String buyer_bank;
	private String buyer_bankno;
	private String buyer_bankname;
	private String buyer_zip;
	private String buyer_add1;
	private String buyer_add2;
	private String buyer_comtel;
	private String buyer_fax;
	private String buyer_mail;
	private String buyer_charger;
	private String buyer_telext;
	
	public BuyerVO() {}
	public BuyerVO(String buyer_id, String buyer_name, String buyer_lgu, String buyer_bank, String buyer_bankno,
			String buyer_bankname, String buyer_zip, String buyer_add1, String buyer_add2, String buyer_comtel,
			String buyer_fax, String buyer_mail, String buyer_charger, String buyer_telext) {
		this.buyer_id = buyer_id;
		this.buyer_name = buyer_name;
		this.buyer_lgu = buyer_lgu;
		this.buyer_bank = buyer_bank;
		this.buyer_bankno = buyer_bankno;
		this.buyer_bankname = buyer_bankname;
		this.buyer_zip = buyer_zip;
		this.buyer_add1 = buyer_add1;
		this.buyer_add2 = buyer_add2;
		this.buyer_comtel = buyer_comtel;
		this.buyer_fax = buyer_fax;
		this.buyer_mail = buyer_mail;
		this.buyer_charger = buyer_charger;
		this.buyer_telext = buyer_telext;
	}
	
	public String getBuyer_id() {
		return buyer_id;
	}
	public void setBuyer_id(String buyer_id) {
		this.buyer_id = buyer_id;
	}
	public String getBuyer_name() {
		return buyer_name;
	}
	public void setBuyer_name(String buyer_name) {
		this.buyer_name = buyer_name;
	}
	public String getBuyer_lgu() {
		return buyer_lgu;
	}
	public void setBuyer_lgu(String buyer_lgu) {
		this.buyer_lgu = buyer_lgu;
	}
	public String getBuyer_bank() {
		return buyer_bank;
	}
	public void setBuyer_bank(String buyer_bank) {
		this.buyer_bank = buyer_bank;
	}
	public String getBuyer_bankno() {
		return buyer_bankno;
	}
	public void setBuyer_bankno(String buyer_bankno) {
		this.buyer_bankno = buyer_bankno;
	}
	public String getBuyer_bankname() {
		return buyer_bankname;
	}
	public void setBuyer_bankname(String buyer_bankname) {
		this.buyer_bankname = buyer_bankname;
	}
	public String getBuyer_zip() {
		return buyer_zip;
	}
	public void setBuyer_zip(String buyer_zip) {
		this.buyer_zip = buyer_zip;
	}
	public String getBuyer_add1() {
		return buyer_add1;
	}
	public void setBuyer_add1(String buyer_add1) {
		this.buyer_add1 = buyer_add1;
	}
	public String getBuyer_add2() {
		return buyer_add2;
	}
	public void setBuyer_add2(String buyer_add2) {
		this.buyer_add2 = buyer_add2;
	}
	public String getBuyer_comtel() {
		return buyer_comtel;
	}
	public void setBuyer_comtel(String buyer_comtel) {
		this.buyer_comtel = buyer_comtel;
	}
	public String getBuyer_fax() {
		return buyer_fax;
	}
	public void setBuyer_fax(String buyer_fax) {
		this.buyer_fax = buyer_fax;
	}
	public String getBuyer_mail() {
		return buyer_mail;
	}
	public void setBuyer_mail(String buyer_mail) {
		this.buyer_mail = buyer_mail;
	}
	public String getBuyer_charger() {
		return buyer_charger;
	}
	public void setBuyer_charger(String buyer_charger) {
		this.buyer_charger = buyer_charger;
	}
	public String getBuyer_telext() {
		return buyer_telext;
	}
	public void setBuyer_telext(String buyer_telext) {
		this.buyer_telext = buyer_telext;
	}
	
	@Override
	public String toString() {
		return "BuyerVO [buyer_id=" + buyer_id + ", buyer_name=" + buyer_name + ", buyer_lgu=" + buyer_lgu
				+ ", buyer_bank=" + buyer_bank + ", buyer_bankno=" + buyer_bankno + ", buyer_bankname=" + buyer_bankname
				+ ", buyer_zip=" + buyer_zip + ", buyer_add1=" + buyer_add1 + ", buyer_add2=" + buyer_add2
				+ ", buyer_comtel=" + buyer_comtel + ", buyer_fax=" + buyer_fax + ", buyer_mail=" + buyer_mail
				+ ", buyer_charger=" + buyer_charger + ", buyer_telext=" + buyer_telext + "]";
	}
	
}

[IBuyerService.java]

package kr.or.ddit.buyer.service;

import java.util.List;

import kr.or.ddit.buyer.vo.BuyerVO;

public interface IBuyerService {

	public List<BuyerVO> selectName();
	public BuyerVO selectById(String id);
	
}

[IBuyerDAO.java]

package kr.or.ddit.buyer.dao;

import java.util.List;

import kr.or.ddit.buyer.vo.BuyerVO;

public interface IBuyerDAO {

	public List<BuyerVO> selectName();
	public BuyerVO selectById(String id);
	
}

[mybatis-config.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!-- 이 문서는 MyBatis의 환경 설정을 구성하는 문서입니다. -->
<!DOCTYPE configuration 
	PUBLIC "-//mybatis.org/DTD Config 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- DB연결 정보가 저장된 properties파일에 대한 정보를 설정한다. -->
	<properties resource="kr/or/ddit/mybatis/config/dbinfo.properties" />
	
	<!-- MyBatis 설정과 관련된 기본 setting 설정 -->
	<settings>
		<!-- 데이터가 null로 전달되었으면 빈칸으로 인식하지 말고 null로 인식하라 -->
		<setting name="jdbcTypeForNull" value="NULL" />
	</settings>
	
	<!-- 
		MyBatis에서 파라미터로 사용하는 객체는 패키지명을 포함한 전체 이름을 지정해야 한다. 
		그렇게 되면 전체 이름이 너무 길어질 수 있어서 이것을 짧은 이름으로 사용하기 위한
		별칭을 설정할 수 있다.
		형식) <typeAlias type="패키지명이 포함된 전체 클래스명" alias="별칭이름" />
	-->
	<typeAliases>
		<typeAlias type="kr.or.ddit.member.vo.MemberVO" alias="memberVo" />
		<typeAlias type="kr.or.ddit.lprod.vo.LprodVO" alias="lprodVo" />
		<typeAlias type="kr.or.ddit.buyer.vo.BuyerVO" alias="buyerVo" />
	</typeAliases>
	
	<!-- DB연결 설정 -->
	<environments default="oracleDev">
		<environment id="oracleDev">
			<!-- 오라클 -->
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${user}" />
				<property name="password" value="${pass}" />
			</dataSource>
		</environment>
		<!-- <environment id="m1">
			MySql
		</environment> -->
	</environments>
	
	<!-- DB에서 처리될 SQL문들이 작성된 mapper파일들을 등록하는 부분 -->
	<!-- 형식) <mapper resource="경로명/파일명.xml" /> -->
	<mappers>
		<mapper resource="kr/or/ddit/mybatis/mapper/member.xml" />
		<mapper resource="kr/or/ddit/mybatis/mapper/lprod.xml" />
		<mapper resource="kr/or/ddit/mybatis/mapper/buyer.xml" />
	</mappers>
</configuration>

[buyer.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper 
	PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" 
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="buyer">

	<select id="selectName" resultType="buyerVo">
		select buyer_id, buyer_name from buyer
	</select>
	
	<select id="selectById" parameterType="String" resultType="buyerVo">
		select * from buyer where buyer_id = #{buyer_id}
	</select>
	
</mapper>

[BuyerDaoImpl.java]

package kr.or.ddit.buyer.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

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

/*
 * SqlSession 객체 얻기
 * 싱글톤을 위한 자신의 객체 생성해서 리턴하기
 */
public class BuyerDaoImpl implements IBuyerDAO {

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

	@Override
	public BuyerVO selectById(String id) {
		SqlSession session = null;
		BuyerVO buyerVo = null;
		
		try {
			session = MyBatisUtil.getSqlSession();
			buyerVo = session.selectOne("buyer.selectById", id);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session != null) session.close();
		}
		
		return buyerVo;
	}

}

[BuyerServiceImpl.java]

package kr.or.ddit.buyer.service;

import java.util.List;

import kr.or.ddit.buyer.dao.BuyerDaoImpl;
import kr.or.ddit.buyer.dao.IBuyerDAO;
import kr.or.ddit.buyer.vo.BuyerVO;

public class BuyerServiceImpl implements IBuyerService {

	private IBuyerDAO dao;
	
	// 싱글톤 패턴
	private static BuyerServiceImpl service;
	private BuyerServiceImpl() {
		dao = BuyerDaoImpl.getInstance();
	}
	public static BuyerServiceImpl getInstance() {
		if(service == null) service = new BuyerServiceImpl();
		return service;
	}
	
	@Override
	public List<BuyerVO> selectName() {
		return dao.selectName();
	}

	@Override
	public BuyerVO selectById(String id) {
		return dao.selectById(id);
	}

}

[SelectName.java]

package kr.or.ddit.buyer.controller;

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

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.buyer.service.BuyerServiceImpl;
import kr.or.ddit.buyer.service.IBuyerService;
import kr.or.ddit.buyer.vo.BuyerVO;


@WebServlet("/SelectName.do")
public class SelectName 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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		IBuyerService service = BuyerServiceImpl.getInstance();
		List<BuyerVO> buyerList = service.selectName();
		request.setAttribute("buyerList", buyerList);
		RequestDispatcher disp = request.getRequestDispatcher("/0926/buyerListAll.jsp");
		disp.forward(request, response);
		
	}

}

[buyerListAll.jsp]

<%@page import="kr.or.ddit.buyer.vo.BuyerVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	List<BuyerVO> buyerList = (List<BuyerVO>) request.getAttribute("buyerList");
%>
[
	<% 
		for(int i=0; i<buyerList.size(); i++) {
			BuyerVO vo = buyerList.get(i);
			if(i > 0) out.print(",");
	%>
		{
			"id" : "<%= vo.getBuyer_id() %>",
			"name" : "<%= vo.getBuyer_name() %>"
		}
	<% 
		}
	%>
]

[ajaxTest04.html]

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax04" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax04" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax04</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;
            }
            #result1 table {
                border-collapse: collapse;
                border: 1px solid blue;
                width: 100%;
            }
            #result1 th {
                background-color: blue;
                color: white;
                height: 50px;
            }
            #result1 th:first-of-type {
                width: 30%;
            }
            #result1 th:last-of-type {
                width: 70%;
            }
            #result1 ul {
                list-style: none;
            }
            #result1 li {
                padding: 10px;
                cursor: pointer;
                transition: all 0.4s;
            }
            #result1 li:hover {
                background-color: orange;
                color: white;
            }
        </style>
        <script>
            
            $(function(){
                
                // 일반 구매자 정보 뿌리고 시작.
                $.ajax({
                    url : "/jqpro/SelectName.do",
                    type : "get",
                    success : function(res){
                        var code = `<ul>`;
                        $.each(res, function(i, v){
                            code += `<li data="${v.id}">${v.name}</li>`;
                        })
                        code += `</ul>`;
                        
                        $("#buyerAll").append(code);
                    },
                    error : function(xhr){
                        alert("상태 : " + xhr.status);
                    },
                    dataType : 'json'
                });
                
            });
            
        </script>
    </head>
    <body>

        <hr color="red" /> 
        
        <h1>
            Ajax04 실습 1-1
            <br />
            buyerExample.html
        </h1>
        
        <div id="result1">
            <table border="1">
                <tr>
                    <th>거래처이름</th>
                    <th>거래처상세정보</th>
                </tr>
                <tr>
                    <td id="buyerAll"></td>
                    <td id="buyerInfo"></td>
                </tr>
            </table>
        </div>
        
        <hr color="red" />
   
    </body>
</html>


[SelectById.java]

package kr.or.ddit.buyer.controller;

import java.io.IOException;

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.buyer.service.BuyerServiceImpl;
import kr.or.ddit.buyer.service.IBuyerService;
import kr.or.ddit.buyer.vo.BuyerVO;


@WebServlet("/selectById.do")
public class SelectById 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 buyerId = request.getParameter("buyerId");
		IBuyerService service = BuyerServiceImpl.getInstance();
		BuyerVO vo = service.selectById(buyerId);
		request.setAttribute("resultVo", vo);
		RequestDispatcher disp = request.getRequestDispatcher("/0926/buyerSelectOne.jsp");
		disp.forward(request, response);
	}

}

[buyerSelectOne.jsp]

<%@page import="kr.or.ddit.buyer.vo.BuyerVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	BuyerVO vo = (BuyerVO) request.getAttribute("resultVo");
	if(vo != null) {
		
%>

	{
		"res" : "ok",
		"id" : "<%= vo.getBuyer_id() %>",
		"name" : "<%= vo.getBuyer_name() %>",
		"lgu" : "<%= vo.getBuyer_lgu() %>",
		"comtel" : "<%= vo.getBuyer_comtel() %>",
		"bank" : "<%= vo.getBuyer_bank() %>",
		"bankno" : "<%= vo.getBuyer_bankno() %>",
		"bankname" : "<%= vo.getBuyer_bankname() %>",
		"mail" : "<%= vo.getBuyer_mail() %>",
		"zip" : "<%= vo.getBuyer_zip() %>",
		"addr" : "<%= vo.getBuyer_add1() + " " + vo.getBuyer_add2() %>"
	}

<%
	}else{
%>	

	{
		"res" : "no"
	}

<%
	}
%>

[ajaxTest04.html]

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax04" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax04" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax04</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;
            }
            #result1 table {
                border-collapse: collapse;
                border: 1px solid blue;
                width: 100%;
            }
            #result1 th {
                background-color: blue;
                color: white;
                height: 50px;
            }
            #result1 th:first-of-type {
                width: 30%;
            }
            #result1 th:last-of-type {
                width: 70%;
            }
            #result1 ul {
                list-style: none;
            }
            #result1 li {
                padding: 10px;
                cursor: pointer;
                transition: all 0.4s;
            }
            #result1 li:hover {
                background-color: orange;
                color: white;
            }
        </style>
        <script>
            
            $(function(){
                
                // 일반 구매자 정보 뿌리고 시작.
                $.ajax({
                    url : "/jqpro/SelectName.do",
                    type : "get",
                    success : function(res){
                        var code = `<ul>`;
                        $.each(res, function(i, v){
                            // code += `<li data="${v.id}">${v.name}</li>`;
                            code += `<li>${v.name}<input type='hidden' value='${v.id}' /></li>`;
                        })
                        code += `</ul>`;
                        
                        $("#buyerAll").append(code);
                    },
                    error : function(xhr){
                        alert("상태 : " + xhr.status);
                    },
                    dataType : 'json'
                });
                
                $(document).on("click", "#buyerAll li", function(){
                	
                	$("#buyerInfo").empty();
                	
                	//var buyerId = $(this).attr("data");
                	var buyerId = $(this).find("input").val();
                	//console.log(buyerId);
                	
                	$.ajax({
                		url : "/jqpro/SelectById.do",
                		type : "post",
                		data : {"buyerId" : buyerId},
                		success : function(res){
                			if(res.res == "ok"){
                				var code = `<ul>`;
                				code += `<li><span>BUYER_ID</span><span>${res.id}</span></li>`;
                				code += `<li><span>BUYER_NAME</span><span>${res.name}</span></li>`;
                				code += `<li><span>BUYER_LGU</span><span>${res.lgu}</span></li>`;
                				code += `<li><span>BUYER_COMTEL</span><span>${res.comtel}</span></li>`;
                				code += `<li><span>BUYER_BANK</span><span>${res.bank}</span></li>`;
                				code += `<li><span>BUYER_BANKNO</span><span>${res.bankno}</span></li>`;
                				code += `<li><span>BUYER_BANKNAME</span><span>${res.bankname}</span></li>`;
                				code += `<li><span>BUYER_MAIL</span><span>${res.mail}</span></li>`;
                				code += `<li><span>BUYER_ZIP</span><span>${res.zip}</span></li>`;
                				code += `<li><span>BUYER_ADD</span><span>${res.addr}</span></li>`;
                				code += `</ul>`;
                				
                				$("#buyerInfo").append(code);
                				
			                	$("#buyerInfo span").css({
			                		display: "inline-block",
			                		width: "50%"
			                	});
			                	
                			}else {
                				alert("일치하는 데이터가 없습니다.");
                				return false;
                			}
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
            });
            
        </script>
    </head>
    <body>

        <hr color="red" /> 
        
        <h1>
            Ajax04 실습 1-1
            <br />
            buyerExample.html
        </h1>
        
        <div id="result1">
            <table border="1">
                <tr>
                    <th>거래처이름</th>
                    <th>거래처상세정보</th>
                </tr>
                <tr>
                    <td id="buyerAll"></td>
                    <td id="buyerInfo"></td>
                </tr>
            </table>
        </div>
        
        <hr color="red" />
   
    </body>
</html>

- http://localhost/jqpro/0926/ajaxTest04.html

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

231004_AJAX 강의  (0) 2023.10.02
230927_AJAX 강의  (0) 2023.09.27
230925_AJAX 강의  (0) 2023.09.25
230922_AJAX 강의  (0) 2023.09.22
230921_AJAX 강의  (0) 2023.09.21