스프링 mvc - 3

김성지·2022년 4월 21일
0

스프링기초

목록 보기
7/13

modelattribute

@ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@ModelAttribute HelloData helloData){
        log.info("username={},age={}",helloData.getUsername(),helloData.getAge());
        return "ok";
    }

뒤에 /username-hello&age=20 가 붙으면 핸들러의 매개변수인 hellodata 에 알아서 매핑된다.
다음에는 hellodata객체가 자동으로 model객체에 추가됨, 뷰단으로 전달되게 된다.
즉 사용자가 요청시 전달하는 값을 오브젝트 형태로 매핑해주는 어노테이션이다.

@RequestParam

@ResponseBody
    @RequestMapping("/request-param-map")
    public String requestParamMap(@RequestParam Map<String,Object> paramap){

        log.info("username={}, age={}",paramap.get("username"),paramap.get("age"));
        return "ok";
    }

또는

@ResponseBody
    @RequestMapping("/request-param-v3")
    public String requestParamV3(
            @RequestParam String username,
            @RequestParam int age){
        log.info("username={}, age={}",username,age);

        return "ok";
    }

특징 @RequestParam 이 지정한 키값이 존재하지 않으면 BadRequest로 http 400번대 에러가 발생함 이때 Defalutvalue를 지정해 줄 수 있음

HashMap으로 통째로 받아올 수도 있다.!

PathVariable

@GetMapping("/mapping/users/{userId}/orders/{orderId}")
    public String mappingPath(@PathVariable String userId,@PathVariable Long orderId){
        log.info("mappingPath userId={}, orderId={}",userId,orderId);
        return "ok";
    }

@ResponseBody

view 조회를 무시하고, HTTP message body에 직접 해당 내용 입력한다.

HttpServletRequest

  1. @PostMapping
  2. Http message body에 데이터를 직접 담아서 요청하는 방식
  3. HttpEntity<>
  4. 요청 파라미터 vs HTTP 메시지 바디
  5. @RequestBody
  6. HTTP 응답 - 정적 리소스, 뷰 템플릿

RestController

레스트 컨트롤러는 반환 값으로 뷰를 찾는 것이 아니라, HTTP 메시지 바디에 바로 입력한다. @ResponseBody와 관련이 있음

함수가 다양한 인자값들을 가질 수 있는 이유

0개의 댓글