[Spring] Path Variable, Request Param

Jiwoo·2024년 5월 28일
0

Spring

목록 보기
2/19

📌 Path Variable

  • 브라우저에서 서버로 HTTP 요청을 보낼 때 데이터 함께 보낼 수 있다
@Controller
@RequestMapping("/hello/request")
public class RequestController {
    @GetMapping("/form/html")
    public String helloForm() {
        return "hello-request-form";
    }
}

🌐 GET http://localhost:8080/hello/request/star/Robbie/age/95

  • 서버에 보내려는 데이터를 URL 경로에 추가 가능

// [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
    return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
  • 데이터를 받기 위해서는 URL 경로에서 데이터를 받고자 하는 위치의 경로에 {data} 중괄호 사용

  • 해당 요청 메서드 파라미터에 @PathVariable 과 함께 {name} 중괄호에 선언한 변수명과 변수타입을 선언하면 해당 경로의 데이터 받아올 수 있다.

📌 Request Param

🌐 GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95

  • 서버에 보내려는 데이터를 URL 경로 마지막에 ?와 $ 사용해 추가

// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
    return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
  • (@RequestParam String name, @RequestParam int age)
    @RequestParam 과 함께 key 부분에 선언한 변수명과 변수타입 선언하면 데이터 받아올 수 있다.

form 태그 POST

🌐 POST http://localhost:8080/hello/request/form/param

  • HTML의 form 태그 사용해 POST 방식으로 HTTP 요청 보냄

0개의 댓글