Light Blue Pointer
본문 바로가기
Developing/개발일지

2023-11-07, Today I Learned

by Greedy 2023. 11. 7.

오늘 공부한 것

 

[내일배움캠프][Spring][1주차]데이터를 클라이언트에게 반환하는 방법

데이터를 클라이언트에게 반환하는 방법 프론트엔드 : 클라이언트 쪽 개발 백엔드 : 서버쪽 개발 느슨하게 결합하는 방식이 점점 더 많이 채택되고 있음 AJAX 로 요청이 들어오면 JSON 데이터 요청

greedydeveloper.tistory.com

 

[내일배움캠프][Spring][1주차]Jackson이란 무엇일까

스프링이 3.0 이후로 Jackson과 관련된 API를 제공해서 우리가 코드를 직접 작성해서 JSON 데이터를 처리하지 않아도 된다고 함 external libraries 에 jackson이라는 라이브러리가 자동으로 추가되어있음

greedydeveloper.tistory.com

 

[내일배움캠프][Spring][1주차]Path Variable과 Request Param

Path Variable Client 즉, 브라우저에서 서버로 HTTP 요청을 보낼 때 데이터를 함께 보낼 수 있다. 서버에서는 이 데이터를 받아서 사용해야하는데 데이터를 보내는 방식이 한 가지가 아니라 여러 가지

greedydeveloper.tistory.com

 

[내일배움캠프][Spring][1주차]HTTP 데이터를 객체로 처리하는 방법

request→Star클래스 만듦 우클릭 → generate → Constructor ctrl로 전부 체크 public Star(String name, int age) { this.name = name; this.age = age; } 모든 필드 체크하면 이게 뜸 @ModelAttribute Body 부분에 데이터가 들어왔

greedydeveloper.tistory.com

 

[내일배움캠프][Spring][1주차]메모장 프로젝트 설계 &CRUD

메모장 프로젝트 설계 새 Spring 프로젝트 생성하고 web, lombok, thymeleaf 추가해줌 일단 프론트 파트를 만듦 resources→static→index.html // 사용자가 내용을 올바르게 입력하였는지 확인합니다. function isV

greedydeveloper.tistory.com

오늘 알게된 것

오늘은 클라이언트에서 데이터를 받아오는 방법에 대해서 배웠다

 

1. 그냥 @Controller만 달려 있을때 String 값을 반환을 하면 그 html을 templates에서 찾는데 html이 아니고 데이터를 반환하고 싶을때는 @ResponseBody를 달아줘야 함

 

2. RestController = Controller + ResponseBody

@ResponseBody 안 달아도 자동으로 적용된다

 

3. Getter,Setter 혹은 오버로딩된 생성자가 있어야만 객체를 매개변수로 전달 가능하다

 

4. Jackson 라이브러리를 사용해서 객체↔ JSON(String) 전환이 가능하다.

5. 객체를 매개변수로 해서 데이터를 주고받을때는 Getter,Setter 혹은 오버로딩된 생성자가 필요하다

Star star = new Star("Margot", 33);

ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
String json = objectMapper.writeValueAsString(star);
String json = "{\\\\"name\\\\":\\\\"Robbie\\\\",\\\\"age\\\\":95}"; // JSON 타입의 String

ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper

Star star = objectMapper.readValue(json, Star.class);
System.out.println("star.getName() = " + star.getName());

 

6. 클라이언트에서 데이터를 받아오는 방법에는 여러가지가 있다

 

클라이언트에서 데이터를 받아오는 방법 1

  • Path Variable 방식 → Primitive 타입으로 받는다
<script>
  // GET /star/{name}/age/{age}
  const helloPathForm = document.querySelector("#helloPathFormSend")
  helloPathForm.onclick = (e) => {
    const form = document.querySelector("#helloPathForm");
    const name = form.querySelector('input[name="name"]').value;
    const age = form.querySelector('input[name="age"]').value;
    const relativeUrl = `/hello/request/star/${name}/age/${age}`;
    window.location.href = relativeUrl;
  }
</script>

경로에 데이터 전송하고 싶은 위치에 {data} 중괄호 사용하여

html에서 다음과 같이 /hello/request/star/${name}/age/${age} 데이터를 전송

// [Request sample]
// GET <http://localhost:8080/hello/request/star/Margot/age/33>
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
    return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}

 

 

클라이언트에서 데이터를 받아오는 방법 2

  • Request Param (GET)방식 → Primitive 타입으로 받는다
// [Request sample]
// GET <http://localhost:8080/hello/request/form/param?name=Margot&age=33>
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
    return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

http://localhost:8080/hello/request/form/param 일단 여기서 path가 끝나고

그 후는 Query String 형식(?name=Margot&age=33)으로 데이터를 전송함

?Key=Value&Key=Value 형식임!

 

클라이언트에서 데이터를 받아오는 방법 3

  • Request Param (POST) 방식

7. HTML의 form tag 방식으로 보낼 수 있다

<form method="POST" action="/hello/request/form/model">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
    <button>전송</button>
</form>

요청이 Body 부분으로 넘어감

// [Request sample]
// POST <http://localhost:8080/hello/request/form/param>
// Header
//  Content type: application/x-www-form-urlencoded
// Body
//  name=Margot&age=33
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
    return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

8. POST 방식은 GET 방식과는 다르게 HTTP Body 부분을 가지고 있다

9. Request Param은 생략이 가능하다

10. required 옵션을 false로 하면 null 값이 들어와도 오류가 발생하지 않는다(Path Variable, Request Param 모두 마찬가지)

@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam**(required = false)** String name, int age) {
     return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

 

클라이언트에서 데이터를 받아오는 방법 4

  • Model Attribute 방식 → QueryString을 객체로 받는다

Body 부분에 들어온 QueryString 방식의 데이터를 객체에 매핑해서 가지고 옴

// [Request sample]
// POST <http://localhost:8080/hello/request/form/model>
// Header
//  Content type: application/x-www-form-urlencoded
// Body
//  name=Margot&age=33
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
    return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}

11. @ModelAttribute을 사용할때는 클라이언트에서 전송하는 Query String의 key값이 객체의 field명과 일치해야 한다

객체를 매개변수로 사용할때는 Getter,Setter 혹은 오버로딩된 생성자가 꼭 있어야 한다

클라이언트에서 데이터를 받아오는 방법 5

  • Request Body 형식 → JSON을 객체로 받는다
// [Request sample]
// POST <http://localhost:8080/hello/request/form/json>
// Header
//  Content type: application/json
// Body
//  {"name":"Margot","age":"33"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
    return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}

객체를 매개변수로 사용할때는 Getter,Setter 혹은 오버로딩된 생성자가 꼭 있어야 한다

'Developing > 개발일지' 카테고리의 다른 글

2023-11-09, Today I Learned  (0) 2023.11.09
2023-11-08, Today I Learned  (0) 2023.11.08
2023-11-03, Today I Learned  (0) 2023.11.03
2023-11-02, Today I Learned  (1) 2023.11.02
2023-11-01, Today I Learned  (1) 2023.11.01