Notice
Recent Posts
Recent Comments
Link
archive
[Spring] @RestController 본문
Spring MVC Controller에서는 View를 반환하는 경우도 있고, Data만을 반환하는 경우가 있다.
Spring에서 컨트롤러를 지정해주기 위한 어노테이션에는 @Controller와 @RestController가 있다.
그 중 Data만을 반환하는 경우에 @RestController를 사용한다.
● Person객체의 정보를 웹 화면에 나타내기
먼저, Person class 를 아래와 같이 작성하였다.
package com.study.week01.person;
public class Person {
private String name;
private int age;
private String job;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getJob() {
return job;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setJob(String job) {
this.job = job;
}
}
Controller패키지안에 PersonController.java 파일을 만든다.
package com.study.week01.controller;
import com.study.week01.person.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@GetMapping("/myinfo")
public Person getPerson(){
Person me = new Person();
me.setAge(20);
me.setName("james");
me.setJob("student");
return me;
}
}
@GetMapping : GET방식으로 들어온 요청을 처리하는 메소드를 나타내는 어노테이션이다.
즉, localhost:8080/myinfo 경로로 request가 들어오면 PersonController메소드가 실행된다.
현재 메소드에서 Person객체를 반환하고 있다. 이 객체가 자동으로 JSON객체로 변환되어 클라이언트로 전송한다.
'STUDY > Spring' 카테고리의 다른 글
REST API 실습 (0) | 2021.01.26 |
---|---|
JPA란? / Domain, Repository, Service / CRUD실습 (0) | 2021.01.21 |
Port 8080 was already in use 오류 해결법 (mac OS) (0) | 2021.01.18 |
Spring 웹 개발 기초 (0) | 2021.01.18 |
[Spring Boot] Welcome page 만들기 (0) | 2021.01.15 |
Comments