보통은 @Controller
어노테이션을 이용하여 Controller
를 생성했을때, (ViewResolver에 의해) return 값으로 반환하는 문자열 이름의 view 페이지를 띄어준다. (아래 예시 코드 참고)
HelloCotroller.java
<java />
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public String helloWorld() {
return "helloworld";
}
}
context.xml (View Resolver 설정)
<html />
...
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp" />
</bean>
...
만약, View 페이지가 아닌 반환값 그대로 클라이언트한테 return 하고 싶은 경우 @ResponseBody
를 사용하면 된다.
1. @ResponseBody
만약 @ResponseBody
를 사용하지 않고 아래와 같이 코드를 작성하면, helloworld.jsp
라는 찾는다.
하지만, helloworld.jsp
를 생성하지 않았기 때문에, view 페이지를 찾지 못해서 아래와 같이 500 Internal Server Error
가 발생한다.
![](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
view 페이지가 아닌 helloworld
라는 문자열을 그대로 반환하고 싶다면, 해당 메소드 위에 @ResponseBody
를 추가한다.
<java />
@ResponseBody
@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public String helloWorld() {
return "helloworld";
}
그리고 다시 확인해보면, 아래와 같이 return 값 그래도 Client한테 반환한다.
![](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
문자열이 아닌 VO 객체를 반환해도 된다. 객체를 반환하게 되면, json 형태로 반환한다.
![](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
다른 방법으로도 위와같이 API를 만들 수 있다. (아래 글 참고)
https://memostack.tistory.com/244
@RestController 를 이용하여 REST API 개발
@Controller 어노테이션을 이용하면 기본적으로 view 페이지를 찾아서 띄어주는 역할을 한다. 하지만 REST API 를 개발해야하는 상황이라면 각 메소드마다 @ResponseBody 를 붙여서 데이터를 그대로 반환
memostack.tistory.com
'Backend > Spring' 카테고리의 다른 글
Spring의 AOP 개념 (Aspect Oriented Programming) (0) | 2021.03.11 |
---|---|
Spring의 IoC 컨테이너 (Inversion of Control) (0) | 2021.03.10 |
Spring의 DI 개념 (Dependency Injection) (2) | 2021.03.10 |