반응형
요청 매핑
HTTP 메서드를 축약한 애노테이션 사용
@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
public String mappingGetV1() {
log.info("mappingGetV1");
return "ok";
}
@GetMapping(value = "/mappring-get-v2")
public String mappingGetV2() {
log.info("mapping-get-v2");
return "ok";
}
매핑에 경로 변수를 사용
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
매핑에 경로변수를 여러개 사용
@GetMapping("/mapping/users/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
log.info("mappingPath userId={}, orderId={}", userId, orderId);
return "ok";
}
파라미터에 특정 정보를 가져야 매핑되는 경우
@GetMapping(value = "/mapping-param", params = "mode=debug")
public String mappingParam() {
log.info("mappingParam");
return "ok";
}
헤더에 특정 정보를 가져야 매핑되는 경우
@GetMapping(value = "/mapping-header", headers = "mode=debug")
public String mappingHeader() {
log.info("mappingHeader");
return "ok";
}
HTTP 요청 파라미터 - @RequestParam
HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParma 애노테이션도 생략이 가능하다.
//HTTP 파라미터 이름이 변수 이름과 같으면 @RequstParam 애노테이션도 생략 가능해진다.
//변수가 단순 타입이어야 가능하다.(ex String, int, Long)
@ResponseBody
@GetMapping("/request-param-v4")
public String requestParamV4(String username, int age){
log.info("username={} age={}", username, age);
return "ok";
}
파라미터 값을 필수 여부를 설정할 수 있다. (required = true)
//default 값은 true
@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
@RequestParam(required = true) String username,
@RequestParam(required = false) Integer age
) {
log.info("username={} age={}", username, age);
return "ok";
}
파라미터에 값이 없을 경우 기본 값을 설정 할 수 있다. (defaultValue = "value")
@ResponseBody
@RequestMapping("/request-param-default")
public String requestParamDefault(
@RequestParam(required = true, defaultValue = "guest") String username,
@RequestParam(required = false, defaultValue = "-1") int age
) {
log.info("username={} age={}", username, age);
return "ok";
}
요청 파라미터를 Map의 형태로 조회할 수 있다.
@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap) {
log.info("username={}, age={}", paramMap.get("username"),
paramMap.get("age"));
return "ok";
}
@ModelAttribute 애노테이션을 사용해서 요청 파라미터를 객체로 바인딩 할 수 있다.
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={} age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
HTTP 요청 메시지 - 단순 텍스트
HTTPEntity 사용
// HTTP 헤더, 바디 정보를 편리하게 조회할 수 있다.
// 반환할경우에도 메시지 바디 정보를 직접 반환할 수 있다.
@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
String messageBody = httpEntity.getBody();
log.info("messageBody={}", messageBody);
return new HttpEntity<>("ok");
}
@RequestBody 사용
@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) {
log.info("messageBody={}", messageBody);
return "ok";
}
HTTP 요청 파라미터 - JSON
@RequestBody를 사용해서 MessageBody를 HelloData 객체 형태로 받아오고,
@ResponseBody를 사용해서 응답 또한 HelloData 객체 형태로 반환 할 수 있다.
@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData data) {
log.info("username={}, age={}", data.getUsername(), data.getAge());
return data;
}
출처
[인프런] 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의
웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -
www.inflearn.com
반응형
'WEB > Spring 인강' 카테고리의 다른 글
[Spring] 스프링 공부 #26 (0) | 2022.04.14 |
---|---|
[Spring] 스프링 공부 #25 (0) | 2022.04.06 |
[Spring] 스프링 공부 #23 (0) | 2022.04.05 |
[Spring] 스프링 공부 #22 (0) | 2022.04.05 |
[Spring] 스프링 공부 #21 (0) | 2022.04.05 |