웹개발/spring

[Spring] Annotation 종류

동동구링 2022. 8. 3. 17:45

요청을 받는 Annotation

@Controller

  • 요청이 들어오는 스프링 빈
  • 웹 서버를 만드는 프로그램의 가장 앞쪽의 request 전달 받고, response 만들어서 전송하는 곳
  • Dispatcher Servlet 에서 @Controller 들을 스캔

servlet 과 spring 비교

<servlet>

public class HelloController extends HttpServlet {
	
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    	...
    }
}

 

<spring>

@Controller
public class HelloController {
	...
}

@RequestMapping("/ path ")

  • @Controller 스캔한 후 @RequestMapping 을 참조하여 요청한 URL path 와 일치하는 메서드가 수행
  • 클래스 또는 메서드 이름 위에 위치
    • /클래스 경로 / 메서드 경로
  • 메서드 하나 당 페이지 하나를 만들 수 있음
@Controller
@RequestMapping("/ex")
public class HelloController {
	
    @RequestMapping("/hello")
    public String hello() {
    	return "Hello World";
    }	
}

데이터 돌려주는 Annotation

  • 웹 주소로 요청하면 json 등의 데이터를 응답 값으로 보내준다.
  • 이러한 요청을 API(Application Programming Interface) 라고 한다.
  • HttpMessageConverter 가 Annotation 을 보고 메서드 리턴 값에 따라 데이터를 String, Json 등으로 변환한다.

@ResponseBody

  • @Controller 메서드의 리턴 값이 데이터가 되어 response 응답 값의 body 영역에 넣어 보냄
  • Jackson lib 가 설정된 경우 Map 이 리턴되면 Json 으로 변환되어 전송

@RestController

  • @Controller + @ResponseBody
  • @ResponseBody 생략해도 그대로 메서드 리턴 값이 response 응답 값의 body 영역에 넣어 보내짐

ResponseEntity

  • response 의 header 값이나 http status code 를 설정하여 전송
  • response 는 있지만, responseEntity 라는 클래스에 전달 데이터를 포함시켜서 리턴
@RequestMapping("/")
public ResponseEntity<Person> entityResponse() {

	Person person = new Person();
    
    person.setName("dongguring");
    person.setAge(25);
    
    ResponseEntity<Person> entity = new ResponseEntity<>(person, HttpStatus.INTERNAL_SERVER_ERROR);
    
    return entity;
}

<http status code>

  • 200 (OK) : 따로 전달하지 않을 경우 정상
  • 404 (Not Found) : 서버가 요청받은 리소스를 찾을 수 없는 경우
  • 500 (Internal Server Error) : 웹 서버에 문제가 있는 경우
  • 502 (Bad Gateway) : 서버가 다른 서버로부터 유효하지 않은 응답을 받은 경우

 

'웹개발 > spring' 카테고리의 다른 글

[Spring] JSP View 연동  (0) 2022.08.11
[Spring] MyBatis 연동  (0) 2022.08.04
[Spring] 객체 지향 설계와 Spring  (0) 2022.08.04