@Controller
@ResponseBody
@RequestMapping(
value="hello"
)
public class SampleController{
// GET : hello/
@GetMapping()
public void HelloWorld(){
return "Hello World";
}
}
@ResponseBody 어노테이션을 사용해서 자바 객체를 HTTP 응답 본문(body)의 객체로 변환하여 클라이언트로 전송한다.
@RequestMapping은 기본적으로 모든 요청에 대해 유효하다.
→ Get이든 Post이든 value에 해당하는 경로에 요청하면 같은 동작을 수행함.
@GetMapping은 Get 요청에 한해서 유효하다.
@Controller
@ResponseBody
@RequestMapping(
value="hello"
)
public class SampleController{
// GET : hello/
@GetMapping()
public String HelloWorld(){
return "Hello World";
}
/* 파라미터 가져오기 */
// GET : hello/{id}
@GetMapping("{id}") // 이처럼 경로만 필요하면 value를 생략 가능
public int ReteurnParam(
@PathVariable("id") int id
){
//id는 hello/{id}의 id 값을 받아주게 된다.
return id;
}
/* 쿼리값 가져오기 */
// GET : hello/query?id=id
@GetMapping("query")
public int ReturnQuery(
@RequestParam("id") int id
){
return id;
}
/* request의 body 가져오기 */
// GET : hello/body
@GetMapping("body")
public PostData ReturnBody(
@RequestBody PostData postData
){
return postData;
}
/* image 읽어오기 */
// produces : MediaType.IMAGE_PNG_VALUE이므로 png 타입의 이미지를 응답으로 반환
// GET : hello/sample-image
@GetMapping(
value = "/sample-image",
produces = MediaType.IMAGE_PNG_VALUE
)
public byte[] sampleIamge() throws IOException{ //image는 byte[]를 반환함.
//resoures 폴더에서 name에 해당하는 파일을 읽어옴.
InputStream inputStream = getClass().getResourceAsStream("/static/img.png");
return inputStream.readAllBytes();
}
}
Spring 4.x 부터 사용 가능
Spring MVC Controller에 @ResponseBody가 합쳐진 어노테이션
—> 컨트롤러 클래스의 각 메서드마다 @ResponseBody를 추가할 필요가 없음.