[내일배움캠프 사전캠프] 3일 차 TIL Jackson

2026. 2. 6. 18:15·내배캠

Spring 입문 주차 수강

사전캠프 마지막날이다. 원래 2주간 진행되는 사전캠프지만 행정 처리 후 늦게 참여하게 돼서
3일밖에 진행하지 못했지만 3일이라도 열심히 하려고 노력했다.

사전캠프 때 나눠주는 Spring 강의 중 입문 강의를 1-14까지 수강했다.

Spring에서 정적 페이지와 동적 페이지 서빙 하는 법

정적 페이지
static 폴더에 html 파일을 생성하고
컨트롤러에서 return "hello.html";처럼 바로 파일명으로 반환

@GetMapping("static-hello")
public String hello(){
    return "hello.html";
}

이때 Thymeleaf 라이브러리를 추가했다면, 컨트롤러에서 html 파일을 찾는 경로를 /resources/templates로 설정한다.
따라서 컨트롤러를 통해 html 파일을 받고 싶다면
return문 /resources/templates 안에 있는 파일명을 적어야 한다.
ex) return "hello.html"; // 파일이 저장된 경로 -> /resources/templates/hello.html 

타임리프 라이브러리 등록 시 아래와 같이 설정된다.

prefix: classpath:/templates/
suffix:. html

하지만 return "redirect:/hello.html"; 같이 적는다면 static안에 있는 파일을 보내준다.
요청이 http:/localhost:8080/hello.html로 요청이 재 수행되기 때문에 static 폴더의 파일을 반환할 수 있는 것이다.

동적 페이지
Thymeleaf를 통해 Model 객체에 전달할 값을 넣고 ( Model )

return문 안에 thymeleaf 폴더 안 생성한 html 파일명을 적는다. ( View )

 

아래는 페이지 방문 횟수를 Model에 기록하고 View로 전달하는 코드이다.

// 컨트롤러 클래스
private static long visitCount = 0;

@GetMapping("html/dynamic")
public String htmlDynamic(Model model){
    visitCount++;
    model.addAttribute("visits", visitCount);
    return "hello-visit";
}

@ResponseBody

@Controller 안에서는 기본적으로 View 파일을 반환한다.

하지만 메서드 위에 @ResponseBody를 붙이면 문자열 그대로 반환한다.

 

@ResponseBody 사용 시 반환가능한 데이터는
문자열, class객체 등이 있다.
만약 클래스 객체를 반환하면 자동으로 Json형태로 반환한다.

Jackson 라이브러리

Jackson은
Object를 Json 타입의 String으로
Json타입의 String을 Object로 변환해 주는 라이브러리이다.

 

직접 처리할 때는 Jackson 라이브러리의 ObjectMapper를 사용한다.

 

Object to Json)

먼저 변환할 객체와
ObjectMapper 객체의 인스턴스를 생성

Star star = new Star("Robbie", 95); // 변한에 사용할 객체
ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper


그리고 writeValueAsString()을 통해 객체를 String으로 변환

String json = objectMapper.writeValueAsString(star); // 객체를 Json타입의 String으로 변환
System.out.println("json = " + json);

 

Json to Object)

String json = "{\"name\":\"Robbie\",\"age\":95}"; // JSON 타입의 String

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

Star star = objectMapper.readValue(json, Star.class); // Json 타입의 String을 Object로 변환
System.out.println("star.getName() = " + star.getName());
System.out.println("star.getAge() = " + star.getAge());

Json 타입의 String를 readValue()를 통해 Object로 변환할 수 있다.

 

이때 readValue()에서 첫 번째 파라미터에는 변환할 Json타입의 String
두 번째 파라미터에는 변환할 Object의 class 타입을 주면 된다.

 

이때 직렬화는 자바객체(Object)를 문자열(Json)로 변환하는 것을 의미하고
역직렬화는 문자열(Json)을 자바객체(Object)로 변환하는 것을 의미한다.

 

중요한 점은 Jackson은 직렬화 과정에서 해당 객체의 기본생성자와 get 혹은 set 메서드가 필요하다.

@PathVariable  vs @RequestParam

클라이언트가 서버로 요청 시 데이터를 같이 보낸다.
두 어노테이션 다 서버에서 데이터를 받는 방식 중 하나이다.

 

@PathVariable 같은 경우
요청 url 뒤에 슬래시(/)를 붙여서 보낸 요청을 받을 수 있다.
ex) http://localhost:8080/hello/request/star/Robbie/age/95
이때 Robbie와 95는 각각 클라이언트가 name과 age란 값으로 보낸 것이다.

서버에서는 url 경로에 중괄호로 클라이언트의 데이터를 받는다.

// [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
@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);
}

 

@RequestParam의 경우
클라이언트가 쿼리스트링 방식으로 데이터를 보낸다.

// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
@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);
}

서버에서는 @RequestParam을 파라미터에 붙여서 사용한다.
생략이 가능하지만 클라이언트가 해당 값을 보내지 않으면 에러가 난다.
이를 @PathVariable(required = false) 옵션을 붙여 null로 처리할 수도 있다.

 

@ModelAttribute vs @RequestBody

둘 다 클라이언트가 요청 시 보내는 데이터를 서버에서 받을 때 사용하는 어노테이션이다.

@ModelAttributes는 요청 파라미터에 포함된 데이터를 받을 때 사용
- GET 요청 시에는 쿼리 스트링형식으로 온 데이터를 받음

// [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
//  Content type: application/x-www-form-urlencoded
// Body
//  name=Robbie&age=95
@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);
}

 

- Post 요청시에는 body로 들어온 파라미터를 받음

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


@RequestBody는 요청 body에 포함된 데이터를 받을 때 사용
- 요청 body에 JSON형태로 온 데이터를 받음

// [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
//  Content type: application/json
// Body
//  {"name":"Robbie","age":"95"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
    return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}

이때 @ModelAttribute와 @RequestParam의 차이는 
여러 개를 한 번에 받느냐
1개만 받느냐의 차이이다.

그리고 이때 ModelAttribute는 요청 파라미터 body의 데이터를
기본생성자와 setter를 통해 객체에 값을 넣어준다.
중요한 점은 jackson이 사용되지 않는다는 것이고

@RequestBody는 Json타입의 String을 객체로 바꿔주는 것이기에
Jackson이 사용된다.
Post요청일 경우에는 서버에서 Content-type을 보고 결정한다.
application/x-www-urlencoded 라면 ModelAttribute
application/json 이면 @RequestBody + Jackson을 사용한다.

'내배캠' 카테고리의 다른 글

[내일배움캠프 본캠프] 3일 차 TIL 영속성 컨텍스트  (0) 2026.02.12
[내일배움캠프 본캠프] 2일 차 TIL - SQL, JdbcTemplate, IoC, DI, Bean  (0) 2026.02.11
[내일배움캠프 본캠프] 1일 차 TIL 상품-주문 미니프로젝트 피드백  (0) 2026.02.10
[내일배움캠프 사전캠프] 2일 차 TIL 상품-주문 미니프로젝트  (0) 2026.02.05
[내일배움캠프 사전캠프] 1일 차 TIL 상품-주문 미니프로젝트  (0) 2026.02.04
'내배캠' 카테고리의 다른 글
  • [내일배움캠프 본캠프] 2일 차 TIL - SQL, JdbcTemplate, IoC, DI, Bean
  • [내일배움캠프 본캠프] 1일 차 TIL 상품-주문 미니프로젝트 피드백
  • [내일배움캠프 사전캠프] 2일 차 TIL 상품-주문 미니프로젝트
  • [내일배움캠프 사전캠프] 1일 차 TIL 상품-주문 미니프로젝트
MvA
MvA
백엔드 개발자 김재현입니다. 주로 공부하면서 느낀점을 기록합니다.
  • MvA
    Man vs Ai
    MvA
  • 전체
    오늘
    어제
    • 분류 전체보기 (94)
      • Java (6)
      • Python (8)
        • 딥러닝 (1)
        • 머신러닝 (7)
      • JavaScript (2)
      • 내배캠 (60)
      • 개인 프로젝트 (11)
      • 책 후기 (5)
      • 기타 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Riot API
    머신러닝
    TiL
    배포
    내일배움캠프
    딥러닝
    아키텍처
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
MvA
[내일배움캠프 사전캠프] 3일 차 TIL Jackson
상단으로

티스토리툴바