본문 바로가기
Spring

[Spring] MVC2 (4) ajax3 - 4번째 버튼

by moca7 2024. 10. 21.

 

 


ㅁ 4번째 버튼, 4번째 함수 

 

 

- 요청시 전달값 없음. 요청 방식도 생략하면 get방식이라 생략함.

- $.ajax 안에 속성 하나하나 마다 콤마를 붙여줘야 한다.

 

 

 

 

 

ㅁ manage1.jsp 수정

 

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script src="${contextPath}/resources/js/jquery-3.7.1.min.js"></script>

</head>
<body>
    <h3>회원관리 1번 페이지</h3>

    <form id="mem-form">
        번호 : <input type="text" name="userNo"> <br>
        아이디 : <input type="text" name="userId"> <br>
        비밀번호 : <input type="text" name="userPwd"> <br>
       
        <button type="button" onclick="fn_ajax1();">조회1(아이디, 비번으로 이름 조회)</button>
        <button type="button" onclick="fn_ajax2();">조회2(아이디, 비번으로 이름 조회)</button>
        <button type="button" onclick="fn_ajax3()">조회3(번호로 회원전체정보 조회)</button>
        <button type="button" onclick="fn_ajax4()">전체조회</button>
        <br>
       
        <button type="button" onclick="">번외1</button>
        <button type="button" onclick="">번외2</button>
    </form>
   
    <hr>
   
    <div id="result">
        결과가 보여지는 영역
    </div>

    <script>
        // 조회1 버튼 : 아이디랑 비번으로 이름을 조회
        function fn_ajax1() {

            let id = $("input[name=userId]").val();
            let pwd = $("input[name=userPwd]").val();

            $.ajax({
                // 요청
                url: "${contextPath}/member1/detail1.do",
                data: "id=" + id + "&pwd=" + pwd, // 쿼리스트링으로 전달값 작성
                type: "get",

                // 응답
                success: function(resData){
                    $("#result").text(resData);
                },
                error: function(){

                }
            })

        }
   
   
        function fn_ajax2() {
           
            $.ajax({
                url: "${contextPath}/member1/detail2.do",
                type: "get",
                data: $("#mem-form").serialize(), // form의 모든 입력요소들을 직렬화

                success: function(resData){
                    $("#result").text(resData);
                },
                error: function(){
                    console.log("조회2 버튼에 대한 ajax 통신 실패");
                }
               
            })
           
        }


       
        // 회원 전체 정보 조회(1명 - dto)
        function fn_ajax3() {
           
            $.ajax({
                url: "${contextPath}/member1/detail3.do",
                type: "get",
                data: { no: $('input[name=userNo]').val() },

                success: function(resData){
                    console.log(resData);

                    let value = '<ul>'
                                    + '<li>번호: ' + resData.userNo + '</li>'
                                    + '<li>아이디: ' + resData.userId + '</li>'
                                    + '<li>이름: ' + resData.userName + '</li>'
                                + '</ul>';
                               
                    $('#result').html(value);          

                },
                error: function(){
                    console.log("조회3 버튼에 대한 ajax 통신 실패");
                }
               
            })
           
        }


        // 회원 전체 정보 조회(여러명 - list)
        function fn_ajax4() {
           
            $.ajax({
                url: "${contextPath}/member1/list.do",

                success: function(resData){
                    console.log(resData); // [{}, {}, {}]

                    let table = "<table border='1'>";

                    for(let i=0; i<resData.length; i++) {
                        table += '<tr>'
                                    + '<td>' + resData[i].userNo + '</td>'
                                    + '<td>' + resData[i].userId + '</td>'
                                    + '<td>' + resData[i].userName + '</td>'
                                + '</tr>';
                    }  

                    table += "</table>";

                    $('#result').html(table);      

                },
                error: function(){
                    console.log("전체조회 버튼에 대한 ajax 통신 실패");
                }
               
            })
           
        }
   
    </script>
   
</body>
</html>
 

 

 

 

 

ㅁ MemberController1 수정

 

 
package com.br.ajax.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.br.ajax.dto.MemberDto;
import com.br.ajax.service.MemberService;

import lombok.RequiredArgsConstructor;

@RequestMapping("/member1")
@RequiredArgsConstructor
@Controller
public class MemberController1 {

    private final MemberService memService;
   
    private Logger logger = LoggerFactory.getLogger(MemberController1.class);
   

   
    /* 기존의 HttpServletResponse 객체 이용하는 방식

    @GetMapping("/detail1.do")
    public void memberDetail(String id, String pwd, HttpServletResponse response) throws IOException {
        logger.debug("request id: {}, pwd: {}", id, pwd);
        String result = memService.selectMemberByIdPwd(id, pwd);
       
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(result);
    }
    */
   
   
    // Spring 방식
    @ResponseBody
    @GetMapping(value="/detail1.do", produces="text/html; charset=utf-8")
    public String memberDetail(String id, String pwd) {

        logger.debug("request id: {}, pwd: {}", id, pwd);

        String result = memService.selectMemberByIdPwd(id, pwd);
       
        return result;
    }
   
   
    @ResponseBody
    @GetMapping(value="/detail2.do", produces="text/html; charset=utf-8")
    public String memberDetail2(String userId, String userPwd) {
        return memService.selectMemberByIdPwd(userId, userPwd); // 문자열 바로 반환
    }
   
       
    @ResponseBody
    @GetMapping(value="/detail3.do", produces="application/json")
    public MemberDto memberDetail3(@RequestParam(value="no", defaultValue="1") int no) { // 요청시 전달값 받기

        MemberDto mem = memService.selectMemberByNo(no);
        return mem; // {필드명:필드값, 필드명:필드값, ...}
    }
   

    @ResponseBody
    @GetMapping(value="list.do", produces="application/json")
    public List<MemberDto> memberList() {
        List<MemberDto> list = memService.selectMemberList();
        return list; // [{}, {}, {}]
    }

   
}