이전 포스팅 

 

AJAX 기초 수업 개념 정리!!

실습에 앞서 간단한 개념정리를 해본다~~ @ Ajax 란? JavaScript를 사용한 비동기 통신, 클라이언트와 서버간에 데이터를 주고받는 기술이다. 즉, 쉽게 말하자면 자바스크립트를 통해서 서

genie-dev.tistory.com

 

Spring Framework 에서 사용하는 Ajax 샘플 코드를 정리했다. 

 

흐름은 이렇다~~~~ 

1. html에서 Send 버튼을 클릭! 

2. 버튼 클릭 이번트 감지 function 실행

3. 보낼 데이터 준비 후  ajax url(/send)  로 전송~ 

4. @PostMapping(value = "/send") url 컨트롤러 매핑 

5. Controller 안에서 필요한 작업 수행~  

6. $.ajax 안의 success로 콜백 ~! 

7. error 발생 시 $.ajax 안 error 실행 

 

샘플코드로 확인하기! 

 

test.html 

<form id="testForm" method="post">
  이름 : <input type="text" name="name" id="name" value="genie"> <br/>
  나이 : <input type="text" name="age"  id="age" value="29"><br/>
  사는곳 : <input type="text" name="city" id="city" value="seoul"><br/>
  <button id="sendBtn">Send</button>
</form>

 

JS

 $(function() { 
   $("#sendBtn").click(function(e){
     e.preventDefault();


    /***********************
    * 기본 방식
    ************************/
    var form = {
    	name: "genie",
    	age: 29
    }

    $.ajax({
    	url: "/test/form",
    	type: "POST",
      	data: form,
      	success: function(data){
     	 	console.log(data);
      	},
      	error: function(){
          alert("error .. ");
        }
    });


    /***********************
    * form 으로 보내기 
    ************************/
    $.ajax({
      url: "/test/form",
      type: "POST",
      data: $("#testForm").serialize(),
      success: function(data){
     	 console.log(data);
      },
      error: function(){
      	alert("error .. ");
      }
    });





    /***********************
    * stringify 으로 보내기 
    ************************/
    var form2 = {
      name: "genie",
      age: 29
    }

    // 형태 변환 확인해보기 
    console.log(JSON.stringify(form2));  // print : {"name":"genie","age":29}

    console.log(JSON.stringify($('#testForm').serializeArray())); 
    // print : [{"name":"name","value":"genie"},{"name":"age","value":"29"},{"name":"city","value":"seoul"}]

    $.ajax({
      url: "/send",
      type: "POST",
      data: JSON.stringify(form),
      dataType: "json",
      contentType: "application/json; charset=utf-8;",
      success: function(data){
     	 console.log(data)
      },
      error: function(){
     	 alert("error .. ");
      }
    });

  });

});

 

VO

public class UserVO {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 

Controller

@Controller
public class HomeController {
	
	
    @PostMapping("/test/form")
    @ResponseBody
    public String test1(UserVO vo) {
    	
    	/**************************
    	 * vo 에 담긴 param 값 꺼내보기 
    	 **************************/
    	System.out.println("======================");
    	System.out.println("이름 : " + vo.getName());
    	System.out.println("나이 : " + vo.getAge());
    	System.out.println("======================");
    	
    	return "OK";
    }
    
    
    
    @PostMapping(value = "/send")
    public @ResponseBody Map<String, Object> send(@RequestBody Map<String, Object> param){
    	
    	/**************************
    	 * map에 담긴 param 값 꺼내보기 
    	 **************************/
    	System.out.println("======================");
    	System.out.println(param);
    	System.out.println("이름 : " + param.get("name"));
    	System.out.println("나이 : " + param.get("age"));
    	System.out.println("======================");

    	
    	/**************************
    	 * map에서 가져온값 VO에 담아보기 
    	 **************************/
    	UserVO user = new UserVO();
    	user.setName((String) param.get("name"));
    	user.setAge((int) param.get("age"));
    	
    	
    	/**************************
    	 * 객체를 리턴해보기 
    	 **************************/
    	Map<String, Object> res = new HashMap<>();
    	res.put("vo", user);
    	res.put("msg", "OK");
    	
    	
    	return res;
	}
    
}

 

 

끝!! 굳!!!!  

'JAVA 강의 ( 초급)' 카테고리의 다른 글

AJAX 기초 수업 개념 정리!!  (0) 2021.02.18
JSON 에 대해서 알아봅시다.  (0) 2021.02.17
JAVA 기초 3강  (0) 2020.10.04
자바 2강!  (0) 2020.09.26

 

 

Controller에서 @ResponseBody를 사용하는 경우 아래와 같은 에러가 발생한다. 

 

The resource identified by this request is only capable of generating responses with 
characteristics not acceptable according to the request "accept" headers. 

 

 

우선 나의 코드 ! 

 

controller.java

	@ResponseBody
	@RequestMapping(value = "/send", method = RequestMethod.POST)
	public Map<String, Object> send(SendVO sendVO) {
		return sendService.list(sendVO);
	}

 

send.js 

$("#sendBtn").click(function(e) {
		e.preventDefault();
		$.post("/send", $frm.serialize(), function(data, textStatus){
			console.log(data);
			if(textStatus =="success") { 
				var d = JSON.parse(data);
				
		}
	});
});
	

 

 

 

해결방안은 이거다. 

 

pom.xml에 아래 코드를 추가해주면 된다. 

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-core-lgpl</artifactId>
	<version>1.8.1</version>
</dependency>

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-lgpl</artifactId>
	<version>1.8.1</version>
</dependency>

+ Recent posts