스프링에서 응답 데이터를 만드는 방법
/static, /public, /resources, /META_INF/resoures
위의 디렉토리에 정적 리소스를 올리면 톰캣이 해당 데이터를 서빙해준다.
/src/main/resources/static/test.html 파일이 있다면 http://localhost:8080/test.html 로 접근이 가능하다.
뷰 템플릿을 거쳐 HTML이 생성되고, 뷰가 응답을 만들어 전달한다.
/resources/templates
@GetMapping("/response-view-v2")
public String responseViewV2(Model model) {
model.addAttribute("data", "hi!");
return "response/hello";
}
/src/main/resources/template/response/hello.html 파일을 찾아 렌더링한다.
타임리프 의존성을 추가하면 ThymeleafViewResolver
등 필요한 스프링빈을 등록하고 자동으로 다음 설정을 한다.
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
@ResoponseBody 나 HttpEntity 를 사용하면 뷰 템플릿을 사용하는 것이 아니고 Http응답데이터를 출력한다.
@GetMapping("/response-body-string-v3")
public ResponseEntity<HelloData> responseBodyV3(){
HelloData helloData = new HelloData();
helloData.setAge(20);
helloData.setUsername("woowang");
return new ResponseEntity<>(helloData, HttpStatus.ACCEPTED);
}
ResponseEntity를 사용하면 HttpStatus를 동적으로 사용할 수 있다.
@ResponseStatus(HttpStatus.ACCEPTED)
@GetMapping("/response-body-string-v4")
public HelloData responseBodyV4(){
HelloData helloData = new HelloData();
helloData.setAge(20);
helloData.setUsername("woowang");
return helloData;
}
ResponseEntity로 감싸지 않고 바로 반환이 가능하지만 HttpStatus를 정적으로만 설정한다.