본문 바로가기
Spring

[Spring] MVC2 (6) ajax5 - 6번째 버튼

by moca7 2024. 10. 21.

 

 

- 요청시 전달되는 값들을 map으로 바로 받아내는 방법

- Jackson 라이브러리가 있어서 가능한 방법이다.

 

 

 

 

ㅁ 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="fn_etc1()">번외1(응답데이터가 다수일 경우)</button>
        <button type="button" onclick="fn_etc2()">번외2(요청시 전달값 다수를 Map으로 받아보기)</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 통신 실패");
                }
               
            })
           
        }



        // 응답데이터가 다수일 경우 Map에 담아서 반환
        function fn_etc1() {
           
            $.ajax({
                url: "${contextPath}/member1/etc1.do",

                success: function(resData){
                    console.log(resData);
                    console.log('no', resData.no);
                    console.log('list', resData.list);
                    console.log('m', resData.m);

                },
                error: function(){
                    console.log("번외1 버튼에 대한 ajax 통신 실패");
                }
               
            })
           
        }


        // 요청시 전달되는 다수의 파라미터들을 Map으로 받아보기
        function fn_etc2() {
       
            $.ajax({
                url: "${contextPath}/member1/etc2.do",
                type: 'post',
                data: JSON.stringify( { // json 객체 => json 문자열 변환
                    no: 10,
                    name: '김잔디',
                    arr: ['홍길동', '김말똥', 20]
                }),
                contentType: 'application/json',

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

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

 

- 데이터 속성값을 json 방식으로 작성해본다. 숫자 하나, 문자열 하나, 배열 하나.

- 따로따로 변수에 받아내지 않고 곧바로 Map으로 받아낼 수 있다.

그러려면 json 데이터를 문자열로 변환해야 한다. data 속성의 중괄호 블록에 해당하는 ~를 json 문자열로 바꿔야 한다.

그게 바로 javascript~ stringify다.

제이슨 객체를 제이슨 문자열 형식으로 변환해서 전달해야 한다.

- JSON.stringify 함수에 json 객체를 

 

- contentType 속성. 항상 전달되는 값의 타입이다. 요청시 전달되는 값에 대한 타입이다.

 

 

 

 

 

ㅁ ManageController1

 

 
package com.br.ajax.controller;

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

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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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; // [{}, {}, {}, ...]
    }


    @ResponseBody
    @GetMapping(value="etc1.do", produces="application/json")
    public Map<String, Object> responseMapTest() {
       
        // 만일 응답할 데이터로 숫자, List, Dto가 있다는 가정
        Map<String, Object> map = new HashMap<>();
        map.put("no", 1);
        map.put("list", memService.selectMemberList());
        map.put("m", memService.selectMemberByNo(2));

        return map;

        /*
            {
                no: 1,
                list: [{}, {}, {}],
                m: {}
            }
        */

    }



    @ResponseBody
    @PostMapping(value="/etc2.do", produces="application/json")
    public void requestBodyTest(@RequestBody Map<String, Object> map) {
        logger.debug("map: {}", map);
        logger.debug("map>no: {}", map.get("no"));
        logger.debug("map>name: {}", map.get("name"));
        logger.debug("map>arr: {}", map.get("arr")); // list 객체가 나온다. 배열 형태로 출력된다.
    }


}

 

- 메소드의 반환형이 String이든 void든 기본적으로 응답 뷰를 찾는다.

void면 url mapping값~

@ResponseBody ~

 

- 여기서도 @RequestBody를 써야 한다.

 

 

 

 

 

 

 

 

- 문자열 1줄이 넘어간다. 파싱된다.