본문 바로가기

SPRING

API- @ResponseBody

728x90
반응형

http://localhost:8080/hello-string?name=ayon

 

@ResponseBody를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않고

HTTP의 BODY에 문자 내용을 직접 반환한다. (HTML의 <body>가 아님 !!)

단순 문자열인 hello ayon이 출력된다. 페이지 소스 보기 하더라도 소스가 따로 없고 문자열만 나타남.

//문자 반환
@Controller
public class HelloController {
    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
    	return "hello " + name;
    }
}

 

 

 

http://localhost:8080/hello-api?name=ayon

Hello hello = new Hello(); > hello 라는 객체를 생성

hello.setName(name); > hello라는 객체의 name 프로퍼티에 값을 set 해준다.

 

@ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환됨

화면에 {"name" : "ayon"}이 출력된다.

//객체 반환
@Controller
public class HelloController {
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
    	Hello hello = new Hello();
        hello.setName(name);
        return hello;
	}
    
    static class Hello {
    	private String name;
        
        public String getName() {
        	return name;
        }
        
        public void setName(String name) {
        	this.name = name;
        }
    }
}
728x90
반응형

'SPRING' 카테고리의 다른 글

globals.properties 정보에 대한 암호화  (0) 2023.03.16
[Spring] tiles 설명 및 설정 방법  (0) 2023.02.27
MVC 패턴- @RequestParam  (0) 2023.02.20
[Spring] @ResponseBody  (0) 2023.02.17
HttpServletRequest 역할  (0) 2023.02.14