스프링부트 입문 7. Response 내려주기

min seung moon·2021년 6월 26일
0

Spring

목록 보기
24/50

1. 프로젝트 세팅

  • Package : controller
  • Class : ApiController

2. 프로젝트 작성

01. text 테스트(return TEXT)

  • TEXT를 내려주는 일을 흔하지 않다, 흔히 JSON을 내려준다
  • ApiController.java
package com.example.Response.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/text")
    public String text(@RequestParam String account) {
        return account;
    }
}


02. JSON 테스트(Return JSON)

  • 동작 원리
    • request -> object mapper -> object -> method -> object -> object mapper -> json -> response

-1. DTO 생성

  • Package : dto
  • Class : User
  • User.java
package com.example.Response.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
public class User {
    private String name;
    private int age;
    //@JsonProperty("phone_number")
    private String phoneNumber;
    private String address;

    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;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}


-2. Controller 작성

  • ApiController.java
package com.example.Response.controller;

import com.example.Response.dto.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ApiController {

    // TEXT
    @GetMapping("/text")
    public String text(@RequestParam String account) {
        return account;
    }

    // JSON
    // request -> object mapper -> object -> method -> object
    // -> object mapper -> json -> response
    @PostMapping("/json")
    public User json(@RequestBody User user) {
        return user;
    }
}

03. ResponseEntity(명확한 값 전달)

  • 언제나 200이 아닌 경우에 맞는 HTTP Status 전달
  • Response를 내려줄 때 HTTP Status를 지정해주기
  • ApiController.java
package com.example.Response.controller;

import com.example.Response.dto.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ApiController {

    // TEXT
    @GetMapping("/text")
    public String text(@RequestParam String account) {
        return account;
    }

    // JSON
    // request -> object mapper -> object -> method -> object
    // -> object mapper -> json -> response
    @PostMapping("/json")
    public User json(@RequestBody User user) {
        return user; // 200 OK
    }

    // Response를 내려줄 때 HTTP Status를 지정해주기
    @PutMapping("/put")
    public ResponseEntity<User> put(@RequestBody User user) {
        // HttpStatus.CREATED == 201
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
}


04. HTML Return

  • Class : PageController
  • HTML : main.html
    • resources / static / main.html
  • @Controller
    • View를 반환하기 위해 사용되는 어노테이션
    • Data를 반환 시 @ResponseBody 어노테이션을 활용해주며 이를 통해 @Controller도 Json 형태로 데이터를 반환 가능
  • PageController.java
package com.example.Response.controller;

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

@Controller
public class PageController {

    @RequestMapping("/main")
    public String main() {
        return "main.html";
    }
}
  • main.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Main Html Spring Boot
</body>
</html>


05. @Controller에서 JSON 사용

  • @ResponseBody
    • Data를 반환 시 @ResponseBody 어노테이션을 활용해주며 이를 통해 @Controller도 Json 형태로 데이터를 반환 가능
  • int는 기본 0이 셋팅 되기에 int -> Integer로 변경
  • User.java
package com.example.Response.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
public class User {
    private String name;
    private Integer age;
    //@JsonProperty("phone_number")
    private String phoneNumber;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
  • PageController.java
package com.example.Response.controller;

import com.example.Response.dto.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PageController {

    @RequestMapping("/main")
    public String main() {
        return "main.html";
    }

    // ResponseEntity

    @ResponseBody
    @GetMapping("/user")
    public User user() {
        // 자바 11부터 추가가된 타입 추론 타입
        var user = new User();
        user.setName("steve");
        user.setAddress("패스트캠퍼스");
        return user;
    }
}



  • null 값 제외
    • 만약 null 값은 제외하고 싶을 시
    • @JsonInclude(JsonInclude.Include.NON_NULL)
  • User.java
package com.example.Response.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    private String name;
    private Integer age;
    //@JsonProperty("phone_number")
    private String phoneNumber;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

profile
아직까지는 코린이!

0개의 댓글