@RequestBody = 넘어온 파라미터를 자바 객체로 받아준다. http 바디에 있는 값들을 받는것 이므로 json 객체를 받을 때 생략 불가
@RequestParam = 넘어온 파라미터의 name을 받는다.
주로 DTO없이 MAP으로 할때 씀, 이땐 생략 불가
example: @RequestParam Map<String, String> map
@RequestBody로 받기 위해서
조건1 : 컨트롤러의 매개변수를 자바객체로 받는다.
조건2 : 프론트에서 json으로 넘길 경우 JSON.stringify(jsObject)를 사용한다.
자바스크립트 값(객체, Object)을 json으로 바꿔준다.
그럼 서버에선 @RequestBody로 빋고(json으로 받고)
미리 생성된 객체 class로 변환 시켜준다.(jackson library)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$("button").on("click",function(e){
e.preventDefault();
var formObj = $("form").serialize();
console.log(formObj);
$.ajax({
url:"/ajax",
data :JSON.stringify({
"id": "soup",
"pwd" : "billein",
"email" : "shsondd",
"tt":formObj
}),
contentType: 'application/json',
dataType : "json",
type : "post",
error:function(error){
alert(error+"_"+formObj);
},
});
});
});
</script>
<body>
<form action="">
<input type="text" name="t">
<button>전송</button>
</form>
</body>
</html>
@PostMapping("/ajax")
public void bajax(@RequestBody User user){
System.out.println("/b post 컨트롤러");
String id = user.getId();
String pwd = user.getPwd();
String email = user.getEmail();
String tt = user.getTt();
System.out.println(id);
System.out.println(pwd);
System.out.println(email);
System.out.println(tt);
}
콘솔:
/b post 컨트롤러
soup
billein
shsondd
t=jiseong