오늘은 어제에 이어, http에서 요청처리 하는 GET, POST 방식들의 예제들과
데이터베이스의 값을 출력하는 방법에 대해 정리할 예정이다.
✔ @Controller -> HTML 출력
✔ @RestController -> API 서버 생성 의도
GET 방식 - 조회
POST 방식 - 주소와 데이터를 각각 전송
PUT
DELETE
GET : 회원가입 창을 보여주는 것
POST : 회원가입의 정보를 전송
@GetMapping("/register")
public String showForm() {
return "register";
}
-> 단순히 html의 내용을 조회하는 코드.

-> method="post"를 지정함으로써 post방식으로 요청을 보낸다 -> @RequestParam 으로 인해, 요청 파라미터를 받고 출력하는 원리!
AJAX 코드 기본 형태
<script>
async function submitForm() {
const url = "http://localhost:8080/register-ajax2";
const res = await fetch(url, "?name=xx&age=oo");
const data = await res.text();
console.log(data);
}
</script>

front 부분
<script>
async function submitForm() {
const url = "http://localhost:8080/register-ajax2";
const formData = new FormData();
formData.append("name", xx);
formData.append("age", 30);
formData.append("email", tt);
const res = await fetch(url, {
method: "post",
body: formData,
});
const data = await res.text();
console.log(data);
}
</script>
@RequestBody 가 필수이다!<script>
async function submitForm() {
const url = "http://localhost:8080/register-ajax2";
const obj = {
name: xx,
age: 30,
email: tt,
};
const res = await fetch(url, {
method: "post",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(obj),
});
const data = await res.text();
console.log(data);
}
</script>
---
@PostMapping("/register-ajax2")
@ResponseBody
public String registerAjax(
@RequestBody Map<String, Object> body
) {
return body.toString();
}
프로젝트 안에서 static 폴더 안에 있는 파일은, 바로 직접 호출 가능하다.
서버를 2개 사용하고 있을때, 원래 쓰던 서버가 아니면 스프링에서는 JS에 의한 요청은 전부 차단한다. 그래서 아무리 요청을 보내도 반응이 없기 때문에 @CrossOrigin 을 사용하면 요청을 허용한다는 의미이다.
따라서 협업할때, 서버를 다르게 쓸 때 꼭 @CrossOrigin을 써줘야 한다.