티스토리 뷰

728x90

1. 이 포스트는 http://localhost:8080/rest-test/api/students/{ variable } 형식의 요청을 처리한다.

  1-1 { } 안의 변수를 PathVariable이라고 하고 이 값을 받아서 내부적으로 처리 할 수 있디.

 

2. RestController를 다음과 같이 수정한다.

package pe.pilseong.rest_test.restcontroller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import pe.pilseong.rest_test.entity.Student;

@RestController
@RequestMapping("api")
public class StudentController {
  
  List<Student> students = new ArrayList<Student>();
  
  @PostConstruct
  public void loadDefaultData() {
    students.add(new Student("pilseong", "Heo"));
    students.add(new Student("suel", "Heo"));
    students.add(new Student("noel", "Heo"));
  }

  @GetMapping("/students")
  public List<Student> getStudents() {   
    return students;
  }
  
  @GetMapping("/students/{studentId}")
  public Student getStudent(@PathVariable("studentId") int studentId) {
    return this.students.get(studentId);
  }
}

 

  2-1 주제와 상관없지만 구현 편이성을 위해 하드코딩된 데이터를 인스턴스 변수에 두고 사용한다.

    2-1-1 @PostConstruct를 통해서 생성 시에 데이터를 설정한다.

    2-2-2 이전 포스트에 쓴 적이 있듯이 @PostConstruct를 쓰려면 추가라이브러리가 필요하다.

<dependency>
	<groupId>javax.annotation</groupId>
	<artifactId>javax.annotation-api</artifactId>
	<version>1.3.2</version>
</dependency>

    2-2-3 이 내용에 관한 것은 아래 포스트의 8번항목을 참고한다.

 

Spring : Configuration with XML configuration + Spring Annotations

1. 스프링에서 XML설정과 함께 annotation을 사용하면 xml 설정을 줄일 수 있다. 1-1. 스프링에서 annotation을 사용하려면 xml에 component scanning 설정이 필요하다. 1-2. 아래처럼 최상위 package 경로를 설정..

kogle.tistory.com

  2-2 핵심적인 부분은 @PathVariable인데 그 변수를 HTTP method를 통해 {변수}로  받아온다.

    2-2-1 아래 같은 경우 @PathVariable("studentId")에서 괄호 부분이 필요가 없다. 변수가 동일한 경우 생략가능하다.

 

  2-3 결과는 다음 처럼 나온다.

728x90
댓글