새소식

JAVA 교육/Spring

2019/10/16 Ajax 사용법

  • -

Ajax란?

브라우저가 가지고 있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고도 페이지의 일부만을 위한 데이터를 로드하는 기법이며 Ajax를 한마디로 정의하자면 JavaScript를 사용한 비동기 통신, 클라이언트와 서버 간에 XML 데이터를 주고받는 기술이라고 할 수 있겠습니다.

※ 자세한 Ajax를 알고 싶으면 아래 링크를 들어가서 공부해 보자

https://coding-factory.tistory.com/143

 

[Ajax] Ajax란 무엇인가?

▶ Ajax란? Ajax는 JavaScript의 라이브러리중 하나이며 Asynchronous Javascript And Xml(비동기식 자바스크립트와 xml)의 약자입니다. 브라우저가 가지고있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새..

coding-factory.tistory.com

 


Ajax를 배우면서 Ajax가 무엇이고, 어떻게 사용하는 것인지 호스팅을 해보겠습니다. 

1. 기본적인 환경구축

Test를 위해 basicAjax
프로젝트(Spring Legency Project)를 생성

1) 오라클 라이브러리 다운로드 (pom.xml)
2) 한글 필터 등록(web.xml)

※ 한글필터 등록 방법과, 오라클 라이브러리 다운로드는 밑의 게시물에서 확인해 주세요.

https://geminihoroscope.tistory.com/65

 

2019/10/15 Spring 요청 명령어 를 받는 다양한 방식 & Filter(필터)

BbsCont.java 전체 코드 package kr.co.basicspring.test02; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotatio..

geminihoroscope.tistory.com

https://geminihoroscope.tistory.com/68

 

2019/10/16 Maven 라이브러리 다운 방법

pom.xml이란? https://jeong-pro.tistory.com/168 메이븐(Maven)은 알고 스프링(Spring)을 쓰는가? (pom.xml 분석하며 가볍게 정리하는 빌드 툴, Maven) 메이븐(Maven)은 알고 스프링(Spring)을 쓰는가? 제목과 같..

geminihoroscope.tistory.com

 

3) Dynamic Web Project와 구조를 동일하게 하기 위한 환경 구조를 변경

<init-param>의 경로인 /WEB-INF/spring/appServlet/servlet-context.xml 파일을 열어봅시다

 

▼ 본래 servlet-context.xml 파일에서 빨간 상자 부분을 편집해 주겠습니다.

 

▼ 위에 보이는 <resource> 태그를 편집해 주고 prefix의 값을 수정해 주었다.

<?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"
	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 -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Dynamic web Project와 구조를 동일하게 하기위해 환경구조를 변경합니다. -->
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<!-- <resources mapping="/resources/**" location="/resources/" /> -->
	<!-- /webapp폴더를 Frontend단에서 root로 지정 -->
	<default-servlet-handler/>
	
	<!-- 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="/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="kr.co.form1" />
	
</beans:beans>

 

▼ 이제 basicAjax 프로젝트의 webapp이 Dynamic Web Project에서 사용하던 WebContent와 동일해졌기 때문에
 webapp 패키지 안에서 css, js, images, 기타 폴더들을 넣어두고 WebContent처럼 사용하겠습니다.


2. ajaxTest

 
javaScript (본래 페이지 요청 이동 경로)                (서버에서 새로운 페이지로 응답)
idCheck.jsp  ---->  idCheckProc.jsp  ----->  ????
 
Ajax (요청 이동 경로) idCheck.jsp  ---->  서버에서 요청페이지로 응답
                    <----

지금 까지 유효성검사를 하던가 버튼을 클릭해서 발생하는 이벤트 처리를 javascript를 사용해 왔습니다.
javascript는 요청을 하고 요청을 받은 페이지는 새로운 페이지로 응답을 주는 구조입니다

하지만 이렇게 이벤트가 발생을 할때마다 새로운 페이지를 불러 데이터를 가져오는 것은 매우 비효율적이기 때문에
Ajax 라는 라이브러리를 이용해서 요청을 하게되면 요청받은 페이지가 바로 요청을 한 페이지로 응답을 해주는
효율성이 좋은 기능입니다.

 


test

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>01_ajaxTest.jsp</title>
</head>
<body>
 	<button>* 서버에서 응답 받기*</button>
 	<div id="panel"></div>
 	
 	<script src="../js/jquery.js"></script>
 	<script>
 		$("button").click(function(){
 			alert();
 		})//click end
 	</script>
</body>
</html>

ajax 기능 정상 작동

1) 01_ajaxTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>01_ajaxTest.jsp</title>
</head>
<body>
<!-- 
	AJAX(Asynchronous JavaScript And XML)
	- 페이지 전체를 reload하지 않고 일부분만 reload할 수 있다.
	- jQuery 오픈소스중 ajax()함수를 이용한다.
	- 응답받아온 메세지를 처리하는 함수를 callback함수라 한다.
 -->
 	<button>* 서버에서 응답 받기*</button>
 	<div id="panel"></div>
 	
 	<script src="../js/jquery.js"></script>
 	<script>
 		$("button").click(function(){
 			$.ajax({
 				url		:"test.do", 
 				method	:"get",	
 				dataType:"text",	
 				error	:function(){ 
 					
 				},//error end
 				success	:function(){ 
 					
 				}//success 둥
 			});
 		})//click end
 	</script>
</body>
</html>

JSON 형태의 서버 응답 받기
url        : 요청 명령어
method : 보내는 폼형식의 get | post 방식
error     : error 가 발생했을때 callback 함수
success  : 성공하였을때 callback 함수

1. 버튼을 클릭 하면 함수가 발생
2. 함수는 url test.do 명령어에 따라 그에 해당하는 페이지로 이동
3. 보내고 받는 방식은 get 방식이며 문자는 자료형은 text 

2) AjaxTestCont3

package kr.co.form1.test01;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AjaxTestCont {
	public AjaxTestCont() {
		System.out.println("---------------AjaxTestCont() 객체생성");
	}
	
	@RequestMapping("test.do")
	public String ajaxTest(HttpServletRequest req,HttpServletResponse resp) {
		try {
								//평범한 문자열이라는 뜻
			resp.setContentType("text/plain; charset=UTF-8");
			PrintWriter out=resp.getWriter();
			out.println("서버에서 응답해준 메게지:");
			out.println("할게 많아 죽겠다 이녀석아~~~~");
			out.flush();
			out.close();
			
		}catch(Exception e) {System.out.println("응답 실패:"+e);}
		return "";
	}//
}

resp.setContentType("text/plain; charset=UTF-8")   : 응답 요청하는 문자들을 인코딩 해줍니다.

PrintWriter out = resp.getWriter();                      : out 을 사용할 수 있는 객체를 생성해 주었습니다.

결과

 

'JAVA 교육 > Spring' 카테고리의 다른 글

2019/10/17 mymelon  (0) 2019.10.17
2019/10/17 AJax 사용법 2 (JSON, Cookie)  (0) 2019.10.17
2019/10/16 Maven 라이브러리 다운 방법  (0) 2019.10.16
2019/10/16 Spring 로그인 폼  (0) 2019.10.16
DTO 와 VO 의 차이점  (0) 2019.10.16
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.