package com.sparta.springmvc.request;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/hello/request")
public class RequestController {
@GetMapping("/form/html")
public String helloForm() {
return "hello-request-form";
}
// Path Variable => 경로에 값을 넣는 방식
// [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
// PathVariable -> 값을 받는 역할
// PathVariable 이나 다른 방법 선택 할때는 프론트엔드 개발자와 소통 -> api 테이블에 명시
@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);
}
// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
// 쿼리 스트링 방식으로도 불림
// ?name=Robbie&age=95
// RequestParam을 생략가능한데 필수적으로 넣어줘야된다?
// 경우에 따라 변수에 값이 올수도 있고 안 올수도 있을때 -> required = false => 오류안남
// 없을 경우 null이 들어온다
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=Robbie&age=95
// Post방식으로 넘어오는 것을 RequestParam으로 받을 경우
@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);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/model
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=Robbie&age=95
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
// [Request sample]
// GET http://localhost:8080/hello/request/form/param/model?name=Robbie&age=95
// @ModelAttribute는 생략이 가능
// 해당 파라미터가 Simple value(int, Wrapper, Date)타입이면 RequestParam으로 간주 아니면(Object, Class) ModelAttribute로 간주
@GetMapping("/form/param/model")
@ResponseBody
public String helloRequestParam(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
// Content type: application/json
// Body
// {"name":"Robbie","age":"95"} -> Json To Object @RequestBody 사용
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
}