티스토리 뷰

 
0. Spring Boot 시작하기(http://cusonar.tistory.com/2) 에 이어집니다.

1. 먼저 HomeController를 아래와 같이 수정해봅니다.
package com.cusonar.example;

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

@RestController
public class HomeController {
      
       @RequestMapping("/{name}")
       public String home(@PathVariable String name) {
             return "Hello, " + name;
      }
}
 

2. 그리고 localhost:8080/cusonar 에 접속해봅니다.
     . 간단하게 설명드리면 URL에서 cusonar가 message로 매핑이 됩니다. 
     . @RequestMapping에서는 변수를 {}로 감싸주고, 메소드의 파라미터에 @PathVariable과 함께 추가해주시면 됩니다.
     . 메소드에서 파라미터를 활용하면 됩니다.

3. 지금까진 너무 간단하니깐 조금 더 추가를 해보겠습니다. Home 클래스를 추가합니다.
package com.cusonar.example;

public class Home {
       private String name;
       private String message;
      
       public String getName() {
             return name;
      }
       public void setName(String name) {
             this.name = name;
      }
       public String getMessage() {
             return message;
      }
       public void setMessage(String message) {
             this.message = message;
      }
}
 

4. HomeController를 아래와 같이 수정해봅니다.
package com.cusonar.example;

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

@RestController
public class HomeController {
      
       @RequestMapping("/{name}/{message}")
       public Home home(
                   @PathVariable String name,
                   @PathVariable String message) {
            Home home = new Home();
            home.setName(name);
            home.setMessage(message);
            
            return home;
      }
}

5. localhost:8080/cusonar/hello 로 접속해봅니다.
     . @PathVariable은 여러개를 사용할 수 있습니다.
     . 그냥 스트링이 아니라 json 형태로 나오죠? String 뿐 아니라 Object 혹은 Object 배열 모두를 리턴할 수 있습니다. json 형태는 javascript에서 활용하기 편리합니다.
     * json이란? Data를 전달하기 위한 한 방식입니다. Key와 Value의 쌍으로 이루어지며 Key와 Value는 쌍따옴표(")로 감싸줍니다. Key와 Value 사이에는 콜론(:)을 사용하여 구분되어지고, 여러 쌍은 콤마(,)로 구분되며 하나의 객체는 중괄호({})로 여러개의 객체는 대괄호([])로 구분할 수 있습니다.
    
여기까지도 참 쉽죠? 이렇게 간단하게 URL에 변수를 입력받을 수 있도록하는 예제를 살펴보았습니다.

너무 간단해서 도움이 될지 모르겠네요. 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함