Controller 클래스 구현하기

Dami·2023년 11월 2일
0

SPRING

목록 보기
4/14
post-thumbnail

복습) Controller란?

Spring의 꽃 3계층

1) Controller

요청이 날라오면, Service에게 일을 시키는 계층
Service가 일을 해오면, 답장하는 계층
→ 주문을 받는 곳, 주방에 넘겨

2) Service

실질적인 비즈니스 "로직" 일을 하는 계층
일을 할 때 필요한 데이터(연산)를 Repository한테 요청하는 계층
→ 요리를 한다! 주방에서 요리할 때 뭐 필요해? 재료!!

3) Repository

데이터베이스랑 소통하는 역할
→ 재료 준비하는 곳. 재료 사오는 곳!

구현하기

<요구사항>
스프링부트 어플리케이션을 기동시킨 후, 웹브라우저에 ‘localhost:8080/test’ 주소를 입력하면 TEST 글자가 나오게하기

<코드>
MainController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MainController {\
	// http://localhost:8080/test url 요청이 발생하면 messageTest() 메서드가 실행됨
    @GetMapping("/test") 
    @ResponseBody
    public String messageTest() {
        return "TEST";
    }
}

<실행 결과>

어노테이션 + 핸들러

1) @Controller

Spring에서 웹 요청과 응답을 처리하는 Controller정의할 때 사용하는 어노테이션

컨트롤러가 가진 데이터를(서버에서 가져온 거 일 수도 있고,,)
뷰 템플릿이라고 하는 파일에 넣는다!(→ HTML과 비슷한데 동적으로 데이터 포함할 수 있는 것!)

최종적으로 완성된 웹페이지를 사용자의 웹 브라우저에 전송!!

기본적인 Web Controller 클래스를 나타내는 어노테이션
웹 요청과 응답을 처리하는 컨트롤러를 정의할 때 사용

2) @ResponseBody

주로 REST API를 만들 때 자주 사용
이 어노테이션이 사용된 곳은 method에서 return 하는 값이 View를 거치지 않고 HTTP응답 body에 직접 쓰여진다.

3) @RestController

@Controller + @ResponseBody 라고 할 수 있다.
즉 맨 처음에 TEST를 나오게 하는 코드를 다음과 같이 간단하게 바꿀 수 있다.

package com.example.demo;

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

@RestController
public class MainController {
    @GetMapping("/test")
    public String messageTest() {
        return "TEST";
    }
}

4) @GetMapping

GET(조회) 요청을 처리할 때 mapping을 위해 사용되는 어노테이션

즉! 위 코드에서
@GetMapping("/test")는 아래 method는 /test 경로로 들어오는 GET 요청에 대해 실행된다.

다시 말해서
localhost:8080/test 를 조회(GET) 했을 때 'TEST' 문구를 볼 수 있는 것!!

5) @RequestMapping

모든 HTTP 메서드(GET, POST, PUT, DELETE 등)에서 mapping 할 때 사용 가능!

사용 방법 : @RequestMapping("/test")

만약에 특정 HTTP 메서드에서만 쓰고 싶다면?
예를 들어 GET에서만 사용하고 싶다면?
@RequestMapping(value = "/test", method = RequestMethod.GET)

6) Handler

최근 안드로이드 개발에서 일정 동작을 지연시키기 위해 사용했었다

Spring에서는 요청을 실제로 처리하는 것을 의미한다.
즉, @Controller로 정의된 method가 Handler로 작동한다!

다시 정리하자면?
Request로 인해 호출되는 Controller의 method를 의미한다

0개의 댓글