Spring/Springboot-Intellij

[SpringBoot] Spring MVC - Path Variable과 Request Param

congs 2025. 1. 30. 16:03

 

테스트 할 페이지 생성하기! hello-request-form.html 생성

resources-templates-html파일 생성

<!DOCTYPE html>
<html>
<head>
    <title>Hello Request</title>
</head>
<body>
<h2>GET /star/{name}/age/{age}</h2>
<form id="helloPathForm">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
</form>
<div>
    <button id="helloPathFormSend">전송</button>
</div>
<br>

<h2>GET /hello/request/form/param</h2>
<form method="GET" action="/hello/request/form/param">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
    <button>전송</button>
</form>

<br>

<h2>POST /hello/request/form/param</h2>
<form method="POST" action="/hello/request/form/param">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
    <button>전송</button>
</form>
<br>

<h2>POST /hello/request/form/model</h2>
<form method="POST" action="/hello/request/form/model">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
    <button>전송</button>
</form>
<br>

<h2>GET /hello/request/form/param/model </h2>
<form method="GET" action="/hello/request/form/param/model">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
    <button>전송</button>
</form>
<br>

<h2>POST /hello/request/form/json</h2>
<form id="helloJsonForm">
    <div>
        이름: <input name="name" type="text">
    </div>
    <div>
        나이: <input name="age" type="text">
    </div>
</form>
<div>
    <button id="helloJsonSend">전송</button>
</div>
<div>
    <div id="helloJsonResult"></div>
</div>
</body>
<script>
    // GET /star/{name}/age/{age}
    const helloPathForm = document.querySelector("#helloPathFormSend")
    helloPathForm.onclick = (e) => {
        const form = document.querySelector("#helloPathForm");
        const name = form.querySelector('input[name="name"]').value;
        const age = form.querySelector('input[name="age"]').value;
        const relativeUrl = `/hello/request/star/${name}/age/${age}`;
        window.location.href = relativeUrl;
    }

    // POST /hello/request/form/json
    const helloJson = document.querySelector("#helloJsonSend")
    helloJson.onclick = async (e) => {
        const form = document.querySelector("#helloJsonForm");

        const data = {
            name: form.querySelector('input[name="name"]').value,
            age: form.querySelector('input[name="age"]').value
        }

        const response = await fetch('/hello/request/form/json', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })

        const text = await response.text(); // read response body as text
        document.querySelector("#helloJsonResult").innerHTML = text;
    };
</script>
</html>

requestController 생성

새로 request 파일 생성 - RequestController 생성

package com.sparta.springmvc.request;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello/request")
public class RequestController {

    @GetMapping("/form/html")
    public String helloForm() {
        return "hello-request-form";
    }

}


 

Path Variable 방식

  • 서버에 보내려는 데이터를 URL경로에 넣을 수 있음
@GetMapping("/star/{name}/age/{age}")
/star/Robbie/age/95
‘Robbie’와 ‘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);
}

  • 데이터를 받기 위해서는 /star/{name}/age/{age} 처럼
    • URL 경로에서 데이터를 받고자 하는 위치의 경로에 {data} 중괄호를 사용
  • public String helloRequestPath(@PathVariable String name, @PathVariable int age)
    • @PathVariable 애너테이션과 함께 {name} 중괄호에 선언한 변수명과 변수타입을 선언하면, 해당 경로의 데이터를 받아올 수 있음

내용을 작성하고 전송버튼을 누르면
URL에 정보를 담아서 return값이 출력되는 걸 확인가능(상단 URL에서 변경해도 바뀜)

 

 

Request Param 방식

  • 서버에 보내려는 데이터를 URL 경로 마지막에 ? 와 & 를 사용하여 추가
?name=Robbie&age=95
‘Robbie’와 ‘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);
    }
  • 데이터를 받기 위해서는 ?name=Robbie&age=95 에서 
    • key 부분에 선언한 name과 age를 사용하여 / value에 선언된 Robbie, 95 데이터를 받아올 수 있음
  • (@RequestParam String name, @RequestParam int age)
    •  해당 요청 메서드 파라미터에 @RequestParam 애너테이션과 함께 
    • key 부분에 선언한 변수명과 변수타입을 선언하면 데이터를 받아올 수 있습니다

  • 단, @ RequestParam은 생략이 가능하다
  • 하지만  담아오는 값이 없는 경우 에러가 발생하는데!
    • 이를 막기위해 담는 값이 없는 경우에는 @RequestParam(required = false)로 지정하기! = null로 초기화되어옴!
    • 이는 @PathVariable(required = false)도 가능

 

form 태그 POST

  • HTML의 form 태그를 이용하여 POST방식으로 HTTP요청을 보낼 수 있음
  • 이때, 해당 데이터는 HTTP Body에 name="정은"&age=28 형태로 담겨져서 서버로 전달됨
  • Post는 Get과는 다른게 Body가 있음
<form method="POST" action="/hello/request/form/model"> //action은 URL작성
  <div>
    이름: <input name="name" type="text">
  </div>
  <div>
    나이: <input name="age" type="text">
  </div>
  <button>전송</button>
</form>

  • 데이터를 받는 방법은 @RequestParam 애너테이션을 이용하여 받아올 수 있음

// [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
//  Content type: application/x-www-form-urlencoded
// Body
//  name=Robbie&age=95
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
    return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

  • payload : body안에 들어있는 데이터