[ Spring ]/SpringMVC 1편

[Spring] 기본 매핑 / 요청 매핑

쿠릉쿠릉 쾅쾅 2022. 2. 25. 01:39
728x90

 

 

기본 매핑

 

🔍 @RequestMapping

package hello.springmvc.basic.requestmapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController
public class MappingController {

 	private Logger log = LoggerFactory.getLogger(getClass());
    
    /**
     * 기본 요청
     * 둘다 허용 /hello-basic, /hello-basic/
     * HTTP 메서드 모두 허용 GET, HEAD, POST, PUT, PATCH, DELETE
     */
     @RequestMapping("/hello-basic")
     public String helloBasic() {
     	log.info("helloBasic");
     	return "ok";
     }
}
  • @RestController
    • @Controller는 반환타입이 String인 경우 뷰 이름으로 인식된다. 그래서 뷰를 찾고 뷰가 랜더링 된다.
    • @RestController는 반환 값으로 뷰를 찾는 것이 아니라, HTTP 메시지 바디에 바로 입력한다.
  • @ReqeustMapping("/hello-basic")
    • '/hello-basic' URL 호출이 오면 이 메서드가 실행되도록 매핑한다.
    • URL 다중 매핑 가능 : {"/hello-basic", "/hello-go"}

 

 

🔍 다양한 옵션

 

💡 HTTP 메서드 매핑 축약

@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
  • HTTP 메서드 매핑 축약 애노테이션들에게는 @RequestMapping 애노테이션이 들어있다.

 

💡 PathVariable(경로변수) 사용

/**
 * PathVariable 사용
 * 변수명이 같으면 생략 가능
 *
 * @PathVariable("userId") String userId → @PathVariable userId
 * /mapping/userA
 */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
    log.info("mappingPath uerId={}", data);
    return "ok";
}
  • 최근 HTTP API는 다음과 같이 리소스 경로에 식별자를 넣는 스타일을 선호한다.
  • @RequestMapping 애노테이션은 URL 경로를 템플릿화할 수 있다.
  • @PathVariable 애노테이션을 사용하면 매칭되는 부분을 편리하게 조회할 수 있다.

 

/**
 * PathVariable 사용
 * 변수명이 같으면 생략 가능
 *
 * @PathVariable("userId") String userId → @PathVariable userId
 * /mapping/userA
 */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String userId) {
    log.info("mappingPath uerId={}", userId);
    return "ok";
}
  • @PathVariable 애노테이션을 사용할 때 이름과 파라미터 이름이 같으면 해당 애노테이션의 속성 값을 생략할 수 있다.

 

✔ PathVariable 사용 - 다중

/**
 * 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";
}
  • URL 매핑에 경로 변수를 여러개 사용할 경우 @PathVariable을 여러 개 사용하면 된다.

 

@RequestParam vs @PathVariable

@RequestParam

  • http://127.0.0.1?index=1&page=2 형태일 때 사용한다.
  • 파라미터의 값과 이름을 함께 전달하는 방식으로 게시판 등에서 페이지 및 검색 정보를 함께 전달하는 방식으로 사용한다.

 

@GetMapping("/read")
public ModelAndView getFactoryRead(@RequestParam int index, @RequestParam int page) {
   ...    
}
  • 이렇게 쿼리파라미터를 가져올 때 사용한다.

 

@PathVariable

  • http://127.0.0.1/index/1 형태일 때 사용한다.
  • REST API 에서 값을 호출할 때 주로 사용한다.

 

@PostMapping("/delete/{idx}")
@ResponseBody
public JsonResultVo postDeleteFactory(@PathVariable("idx") int factoryIdx) {
	return factoryService.deleteFacotryData(factoryIdx);
}
  • url에서 각 구분자에 들어오는 값을 처리할 때 사용한다.

 

 

💡 특정 파라미터 조건 매핑

/**
 * 파라미터 추가 매핑
 * params="mode"
 * params="!mode"
 * params="mode=debug"
 * params="mode!debug"
 * params= {"mode=debug", "data=good"}
 */
@GetMapping(value = "/mapping-param", params = "mode=debug")
public String mappingParam() {
    log.info("mappingParam");
    return "ok";
}
  • 쿼리파리미터로 넘어온 데이터에 특정 파라미터가 필수로 존재해야 매핑되는 방식이다.
  • 실무에서 자주 사용되지 않는다.

 

💡 특정 헤더 매핑

/**
 * 특정 헤더로 추가 매핑
 * headers="mode"
 * header="!mode"
 * headers="mode=debug"
 * headers="mode!=debug"
 */
@GetMapping(value = "mapping-header", headers = "mode=debug")
public String mappingHeader() {
    log.info("mappingHeader");
    return "ok";
}
  • 파라미터 매핑과 비슷하지만 HTTP 헤더를 사용한다.
  • HTTP request의 헤더에 특정 값이 있을 때만 매핑이 되는 방식이다.
  • 실무에서 잘 안쓰인다.

 

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

/**
 * Context-Type 헤더 기반 추가 매핑 Media Type
 * consumes="application/json"
 * consumes="!application/json"
 * consumes="application/*"
 * consumes="*\/*"
 * MediaType.APPLICATIONS_JSON_VALUE
 */
@PostMapping(value = "/mapping-consume", consumes = "application/json")
public String mappingConsumes() {
    log.info("mappingConsumes");
    return "ok";
}
  • HTTP request의 헤더에 있는 Content-Type 필드 값에 따라 매핑되는 방식이다.
  • Context-Type은 사용자가 보내는 request body의 데이터에 대한 미디어 타입을 의미한다.
  • 만약 맞지 않으면 HTTP 415상태코드(Unsupported Media Type)를 반환한다.

 

consumes = "text/plain"
consumes = {"text/plain", "application/*"}
consumes = MediaType.TEXT_PLAIN_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";
}
  • HTTP request의 헤더에 있는 Accept 필드값에 따라 매핑되는 방식이다.
  • Accept 필드는 사용자가 응답(response)으로 받을 수 있는 데이터에 대한 미디어 타입을 의미한다.
  • 만약 맞지 않으면 HTTP 406 상태코드(Not Acceptable)를 반환한다.

 

produces = "text/plain"
produces = {"text/plain", "application/*"}
produces = MediaType.TEXT_PLAIN_VALUE
produces = "text/plain;charset=UTF-8"

 

 


 

 

요청 매핑 - API

  • 회원 목록 조회 : GET
  • 회원 등록 : POST
  • 회원 조회 : GET
  • 회원 수정 : PATCH
  • 회원 삭제 : DELETE

 

📌 회원 관리 API

package hello.springmvc.basic.requestmapping;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/mapping/users")
public class MappingClassController {

    /**
     * 회원 관리 API
     * 회원 목록 조회: GET
     * 회원 등록: POST
     * 회원 조회: GET
     * 회원 수정: PATCH 
     * 회원 삭제: DELETE
     */

    @GetMapping
    public String user() {
        return "get users";
    }

    @PostMapping
    public String addUser() {
        return "post user";
    }

    @GetMapping("{userId}")
    public String findUser(@PathVariable String userId) {
        return "get userId =" + userId;
    }

    @PatchMapping("/{userId}")
    public String updateUser(@PathVariable String userId) {
        return "update userId= " + userId;
    }

    @DeleteMapping("/{userId}")
    public String deleteUser(@PathVariable String userId) {
        return "delete userId= " + userId;
    }

}
  • @RequestMapping("/mapping/users")
    • 클래스에 해당 애노테이션을 사용해서 애노테이션 속성에 매핑 정보를 적으면, 메서드에서 적혀있는 URL 주소가 합쳐진다.

 

 

 


👀 참고 자료

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의

웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -

www.inflearn.com

 

https://elfinlas.github.io/2018/02/18/spring-parameter/

 

728x90