Web/MVC

EP5. Spring MVC 기본 기능 (요청 매핑)

Spring MVC 기본기능

 

method 별 매핑

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

 

PathVariable

/**
     * PathVariable 사용
     * 변수명이 같으면 생략 가능
     *
     * @PathVariable("userId") String userId -> @PathVariable userId
     * /mapping/userA
     */
    @GetMapping("/mapping/{userId}")
    public String mappingPath(@PathVariable("userId") String data) {
        log.info("mappingPaht userId = {}", data);
        return "ok";
    }

 

변수 이름을 data가 아니라 pathVariable 과 같이 userId로 맞춘다면 

/**
     * PathVariable 사용
     * 변수명이 같으면 생략 가능
     *
     * @PathVariable("userId") String userId -> @PathVariable userId
     * /mapping/userA
     */
    @GetMapping("/mapping/{userId}")
    public String mappingPath(@PathVariable String userId) {
        log.info("mappingPaht userId = {}", userId);
        return "ok";
    }

@PathVariable("userId") 의 ("userId") 부분을 생략할 수 있다.

 

 

 

 

특정조건매핑 (헤더)

    /**
     * 특정 헤더로 추가 매핑
     * headers="mode",
     * headers="!mode"
     * headers="mode=debug"
     * headers="mode!=debug" (! = )
     */
    @GetMapping(value = "/mapping-header", headers = "mode=debug")
    public String mappingHeader() {
        log.info("mappingHeader");
        return "ok";
    }

 

 

 

 

미디어 타입 조건 매핑 HTTP 요청 Content-Type, consume

 

만약 json 으로 요청이온다면 json 으로 리턴해야할 경우가 있다

 

    /**
     * Content-Type 헤더 기반 추가 매핑 Media Type
     * consumes="application/json"
     * consumes="!application/json"
     * consumes="application/*"
     * consumes="*\/*"
     * MediaType.APPLICATION_JSON_VALUE
     */
    @PostMapping(value = "/mapping-consume", consumes = "application/json")
    public String mappingConsumes() {
        log.info("mappingConsumes");
        return "ok";
    }

Controller가 consume(소비)할 수 있는 contetn type 이 application/json 이라는 뜻이다.

application/json 으로 요청이 와야만 처리한다.

 

consumes = MediaType.APPLICATION_JSON_VALUE 도 가능하다

 

 

미디어 타입 조건 매핑 HTTP 요청 Accept, produce

    /*** Accept 헤더 기반 Media Type
     * produces = "text/html"
     * produces = "!text/html"
     * produces = "text/*"
     * produces = "*\/*"
     */
    @PostMapping(value = "/mapping-produce", produces = "text/html")
    public String mappingProduces() {
        log.info("mappingProduces");
        return "ok";
    }

Controller가 content type이 "text/html"인 content를 produce(생산) 한다는 뜻이다.

그래서 클라이언트가 자신이 어떤 컨텐츠를 받아들일 수 있는지 Accept 로 보내준다.

요청이 Accept : "text/html" 이면 처리한다.

 

produces = MediaType.TEXT_HTML_VALUE 도 가능하다

'Web > MVC' 카테고리의 다른 글

EP7. HTTP 응답 데이터 처리  (0) 2021.03.30
EP6. HTTP 요청 데이터 처리  (0) 2021.03.29
EP4. 스프링 MVC 구조  (0) 2021.03.25
EP4. MVC 패턴  (0) 2021.03.22
EP3. 서블릿객체만을 이용해 HTTP 응답 메시지 작성하기  (0) 2021.03.18