hyeonga_code

reProject_04_ajax 알아보기 본문

Project_WEATHERWEAR

reProject_04_ajax 알아보기

hyeonga 2023. 12. 15. 05:59
반응형

2023.12.14

 

- aJax

-- 프로그램 언어가 아님

---- XMLHttpRequest : 웹서버에 데이터를 요청

---- JavaScript, HTML DOM : 데이터 보여주기

-- 페이지 새로고침 없음

-- 서버로부터 데이터 받아 작업 수행

 

-- 동작 과정

1. 웹 페이지에서 이벤트 발생

2. JavaScript가 XMLHttpRequest object 생성

3. 요청 전송

4. 서버에서 실행

5. 서버에서 response 보냄

6. JavaScript에서 response 읽음

7. action 실행

 

-- 형식

$.ajax({ name : value, name : value...});

-- $.ajax() : 비동기로 HTTP 요청

-- $.get() : 전달받은 주소로 get 방식 HTTP 요청

-- $.post() : 전달받은 주소로 post 방식 HTTP 요청

-- getJSON : GET 방식의 HTTP 요청 전송

 

-- async : 비동기_true(default) / 동기_false

-- beforeSend : false 리턴 시 취소

-- cache : 전송 전에 실행, false 리턴 시 취소

-- complete : 요청 완료시 여부 상관없이 실행됨

-- contentType : header의 타입 지정

-- data : 서버로 보낼 데이터 = form 태그의 input 값

-- dataType : 받아올 데이터

-- error: 실패시 실행

-- success : 성공시 실행

---- data : 서버에서 return받은 값

---- textStatus : 상태 설명 문자열

-- type : "GET" / "POST"

-- url : 현재 페이지가 기본값 = form에서의 action

 

-- Servlet / Controller

response.setContentType()을 지정해주어야 response.getWriter()를 호출할 수 있음

 

 

 

-- 실습

1. test를 계속 할 예정이므로 test 할 환경을 세팅합니다.

1) WEB-INF/config 폴더에 test-context.xml 파일 생성

  >>> ".to" 로 호출하지 않는 경우도 있으므로 WEB-INF 폴더와 같은 경로에 test 폴더를 생성할 것이므로 경로가 다름

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    <!-- 의존성 주입을 위해 빈 등록 대신 -->
    <context:component-scan base-package="com.w2.test" />
    
    <!-- Annotation을 활용할 때 기본적인 Default 방식을 설정 -->
    <annotation-driven />
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/test/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
</beans:beans>
 
cs

 

 

2) web.xml 파일에 경로 설정

	<!-- 테스트 설정 -->
	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
				/WEB-INF/config/test-context.xml
				<!-- 사용자 관련 설정 파일 위치 -->
			</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>*.to</url-pattern>
	</servlet-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <!-- root-context 설정 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/applicationContext.xml
            <!-- 기본 설정 컨텍스트 파일 위치 -->
        </param-value>
    </context-param>
    
    <!-- contextConfigLocation에 있는 root-context를 불러옵니다. -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- 테스트 설정 -->
    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/config/test-context.xml
                <!-- 사용자 관련 설정 파일 위치 -->
            </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>*.to</url-pattern>
    </servlet-mapping>
    
    <!-- 사용자 설정 -->
    <servlet>
        <servlet-name>client</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/config/client-context.xml
                <!-- 사용자 관련 설정 파일 위치 -->
            </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>client</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
 
    <!-- 관리자 설정 -->
    <servlet>
        <servlet-name>admin</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/config/admin-context.xml
                <!-- 관리자 관련 설정 파일 위치 -->
            </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>admin</servlet-name>
        <url-pattern>*.mdo</url-pattern>
    </servlet-mapping>
 
    <!-- 인코딩 설정 시작-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!-- Encofing 강제 -->
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
 

 

 

 

-- Get 방식 ajax Test

1. test/ajaxTest.jsp 파일 생성 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexList</title>
    <link rel="stylesheet" href="/w2/resources/admin/admin_css/admin_base_style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h2>Ajax Test</h2>
    
    <h3>1. 버튼 클릭 시 get 방식으로 서버에 데이터 전송 및 응답</h3>
    입력 : <input type="text" id="input1">
    <button id="btn1">전송</button><br>
    응답 : <label id="output1">현재 응답 없음</label>
    <script>
        $(function(){
            $('#btn1').click(function(){
                // 동기식 통신 : location.href= 'url?param';
                // 비동기식 통신 : $.ajax()
                console.log($('#input1').val());
            
                $.ajax({
                    url: '/w2/ajax1.to',
                    type: "GET",
                    dataType: "text",
                    data: {input1: $('#input1').val()},
                    success: function(result){
                        $("#output1").text(result);
                    },
                    error: function(){
                        alert("ajax1 실패");
                    },
                    complete: function(){
                        console.log("ajaxTest1.complete");
                    }
                });
            });
        });
    </script>
</body>
</html>

 

 

2. src/main/java > com.w2.test 패키지 생성 > TestController.java 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.w2.test;
 
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class TestController {
    
    @RequestMapping("ajax1.to")
    public void ajaxTest1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("get ajax");
        String result = request.getParameter("input1");
        System.out.println("result : " + result);
        String re = "전송된 값 : " + result + ", 길이 : " + result.length();
        
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(re);
    }
}
 

 

>>> get 방식으로 값 이동 확인

 

> 1234 입력 후 전송

 

 

 

-- Post 방식으로 ajax Test

1. ajaxTest.jsp 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexList</title>
    <link rel="stylesheet" href="/w2/resources/admin/admin_css/admin_base_style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>    
    <h3>2. 버튼 클릭 시 post 방식으로 서버에 데이터 전송 및 응답</h3>
    입력 1 : <input type="text" id="input2_1"><br>
    입력 2 : <input type="text" id="input2_2"><br>
    <button onclick="test2()">전송</button>
    응답 : <label id="output2">현재 응답 없음</label>
    <script>
        function test2(){
            $.ajax({
                url: '/w2/ajax2.to'// 요청할 주소
                type: "POST",
                dataType: "text",
                data: {
                    input2_1: $("#input2_1").val(),
                    input2_2: $("#input2_2").val()
                }, 
                success: function(result){
                    $("#output2").text(result);
                },
                error: function(){
                    alert("ajax2 실패");
                }
            });
        }            
    </script>
</body>
</html>

 

 

2. TestController.java 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.w2.test;
 
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class TestController {
 
    @PostMapping("ajax2.to")
    public void ajaxTest2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("post ajax");
        String result1 = request.getParameter("input2_1");
        String result2 = request.getParameter("input2_2");
        System.out.println("result1 : " + result1);
        System.out.println("result2 : " + result2);
        String re = "1. 전송된 값 : " + result1 + ", 길이 : " + result1.length()
                + "/ 2. 전송된 값 : " + result2 + ", 길이 : " + result2.length();
        
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(re);
    }    
}
 

 

>> 실행

 

 

>>> 123 / 456 입력 후 전송

 

 

 

-- ajax 처리 후 페이지를 이동하면서 값을 넘길 수 있는지 궁금해졌다.

구글링을 통해 알아보니 post 방식으로는 값을 넘길 수 없고 넘기고 싶은 경우 success function에서 location.href를 통해 파라미터로 넘겨주는 방법밖에 없다고 한다.

 

시도 1. Controller에서 model에 담아 페이지 이동을 실행했으나 실패

시도 2. post 방식으로 location.href에 '.to'로 호출하는 방식도 실패

시도 3. get 방식으로 파라미터로 받아오는 형식

1. ajaxTest.jsp 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexList</title>
    <link rel="stylesheet" href="/w2/resources/admin/admin_css/admin_base_style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h3>3. 버튼 클릭시 get 방식으로 서버에 데이터 전송 후 다른 페이지에서 응답</h3>
    입력 : <input type="text" id="input3"><br>
    <button onclick="test3()">전송</button><br>
    <script>
        function test3(){
            $.ajax({
                url: '/w2/ajax3.to',
                type:"get",
                async: false,
                dataType: "text",
                data: {
                    input3 : $("#input3").val()
                },
                success: function(result){
                    $("output3").text(result);
                    location.href="/w2/ajax3to.to?result=" + result;
                },
                error: function(){
                    alert("ajax3 실패");
                },
                complete: function(){
                    console.log("ajax3 complete");
                }
            });
        }
    </script>
</body>
</html>

 

 

 

2. TestController.java 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.w2.test;
 
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class TestController {
    
    @RequestMapping("ajax3.to")
    public void ajaxTest3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("get 2 ajax to other page");
        
        String result = request.getParameter("input3");
        System.out.println("result : " + result);
        String re = "전송된 값 : " + result + ", 길이 : " + result.length();
        
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(re);
    }
    
    @RequestMapping("ajax3to.to")
    public String ajaxTest3to(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("Move page");
        System.out.println("request : " + request.getParameter("result"));
 
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(request.getParameter("result"));
        return "ajaxResponse";
    }
}
 

 

 

3. 응답할 페이지 ajaxResponse.jsp 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexList</title>
    <link rel="stylesheet" href="/w2/resources/admin/admin_css/admin_base_style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h2>Ajax3</h2>
    응답 : <label id="output3">현재 응답 없음</label><br>
    ${ param.result }
</body>
</html>

 

 

>> 실행

 

 

>>> 123입력 후 전송

반응형