요청이 왔을때 어떤 컨트롤러에서 매핑을 할 것인지 조사해서 매핑을 진행한다.
@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";
}
}
@Controller
: 반환 값이 String
이면 뷰 이름으로 인식된다. 그 결과 뷰를 찾고 뷰가 렌더링 된다.@RestController
: 반환 값으로 뷰를 찾는 것이 아닌, HTTP 메시지 바디에 바로 입력한다. 그 결과 실행 결과로 ok 메시지를 받을 수 있다.@RequestMapping("/hello-basic")
: /hello-basic
URL 호출이 오면 이 메소드가 실행되도록 매핑한다. 다중 설정도 가능하다.method 속성으로 HTTP 메시지를 지정하지 않으면 모든 메서드에 무관하게 호출된다. (GET, HEAD, POST, PUT, PATCH, DELETE)
/**
* method 특정 HTTP 메서드 요청만 허용
* GET, HEAD, POST, PUT, PATCH, DELETE
*/
@RequestMapping("/mapping-get-v1", method = RequestMethod.GET)
public String mappingGetV1() {
log.info("mappingGetV1");
return "ok";
}
method가 GET
인 경우에만 매핑이 되고 다른 방식일 경우 HTTP 405 Method Not Allowed
가 반환된다.
/**
* 편리한 축약 애노테이션
* @GetMapping
* @PostMapping
* @PutMapping
* @DeleteMapping
* @PatchMapping
*/
@GetMapping("/mapping-get-v2")
public String mappingGetV2() {
log.info("mappingGetV2");
return "ok";
}
좀 더 직관적인 방법으로 HTTP 메서드를 축약한 애노테이션을 사용한다. 애노테이션 코드 내부에서 @RequestMapping
, method
를 미리 지정해두었다.
/**
* PathVariable 사용
* 변수명이 같으면 생략 가능
* @PathVariable("userId") String userId -> @PathVariable userId
*/
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String userId) {
log.info("mappingPath userId={}", userId);
return "ok";
}
최근 HTTP API는 리소스 경로에 식별자를 넣는 스타일을 선호한다.
/mapping/userA
/users/1
@RequestMapping
은 URL 경로를 템플릿화 할 수 있는데 @PathVariable
를 사용하면 매칭되는 부분을 편리하게 조회할 수 있다. @PathVariable
의 이름과 파라미터의 이름이 같으면 생략 가능하다.
또한 다음과 같이 다중 사용도 가능하다.
/**
* PathVariable 다중 사용
*/
@GetMapping("/mapping/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable String orderId) {
log.info("mappingPath userId={}, orderId={}", userId, orderId);
return "ok";
}
/**
* 파라미터로 추가 매핑
* params="mode",
* params="!mode"
* params="mode=debug"
* params="mode!=debug" (! = )
* params= {"mode=debug", "data=good"}
*/
@GetMapping(value = "/mapping-param", headers = "mode=debug")
public String mappingParam() {
log.info("mappingParam");
return "ok";
}
특정 파라미터를 조건식으로 매핑해서 매핑 여부를 결정할 수 있다. (잘 사용하진 않음)
/**
* 특정 헤더로 추가 매핑
* 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";
}
헤더 역시 조건 매핑이 가능하다.
/**
* 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";
}
HTTP 415 Unsupported Media Type
을 반환한다./**
* Accept 헤더 기반 MediaType
* produces="text/html",
* produces="!text/html"
* produces="text/*"
* produces="*\/*"
*/
@PostMapping(value = "/mapping-produces", consumes="text/html")
public String mappingProduces() {
log.info("mappingProduces");
return "ok";
}
HTTP 406 Not Acceptable
을 반환한다.@Slf4j
@RestController
public class RequestHeaderController {
@RequestMapping("/headers")
public String headers(HttpServletRequest request,
HttpServletResponse response,
HttpMethod httpMethod,
Locale locale,
@RequestHeader MultiValueMap<String, String> headerMap,
@RequestHeader("host") String host,
@CookieValue(value="myCookie", required=false) String cookie) {
log.info("request={}", request);
log.info("response={}", response);
log.info("httpMethod={}", httpMethod);
log.info("locale={}", locale);
log.info("headerMap={}", headerMap);
log.info("header host={}", host);
log.info("myCookie={}", cookie);
return "ok";
}
}
HttpMethod
: HTTP 메서드를 조회한다. org.springframework.http.HttpMethod
Locale
: Locale 정보를 조회한다. (ko-kr, euc-kr, kr, ...)@RequestHeader MultiValueMap<String, String> headerMap
: 모든 HTTP 헤더를 MultiValueMap 형식으로 조회한다.@RequestHeader("host") String host
: 특정 HTTP 헤더를 조회한다.@CookieValue(value="myCookie", required=false) String cookie
: 특정 쿠키를 조회한다.클라이언트에서 서버로 요청 데이터를 전달할 때는 주로 다음 3가지 방법을 사용한다.
/url?username=hello&age=20
content-type: application/x-www-form-urlencoded
HTTP 요청 메시지를 개발자가 사용하기 편하게 반환하여 제공하는 것이 HttServletRequest
객체이다. 이 객체 내의 getParameter()
를 사용하면 요청 파라미터를 조회할 수 있는데, queryString
으로 요청 메시지를 전달하는 것은 GET 쿼리 파라미터 전송과 POST HTML Form 전송 방식이다.
이 두 방식은 모두 형식이 동일하기 때문에 구분없이 조회할 수 있고 요청 파라미터 조회(request parameter)라 한다.
@Slf4j
@Controller
public class RequestParamController {
@RequestMapping("/request-param-v1")
public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("username");
int age = Integer.parseInt(request.getParameter("age"));
log.info("username={}, age={}", username, age);
response.getWriter().write("ok");
}
}
반환 타입이 없으면서 응답에 값을 직접 입력("ok")하면 view 조회를 할 수 없다. 이전 서블릿 코드를 구현하던 때와 같이 HttpServletRequest
에서 getParameter()
로 요청 파라미터를 조회한다.
@RequestParam
View는 다음과 같다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/request-param-v1" method="post">
username: <input type="text" name="username" />
age: <input type="text" name="age" />
<button type="submit">전송</button>
</form>
</body>
</html>
Controller는 다음과 같은데, 여러 방식으로 요청 파라미터를 사용할 수 있다.
@Slf4j
@Controller
public class RequestParamController {
/**
* @RequestParam: 파라미터 이름으로 바인딩
* @ResponseBody: View 조회를 무시하고, HTTP message body에 직접 해당 내용 입력
*
*/
@ResponseBody
@RequestMapping("/request-param-v2")
public String requestParamV2(
@RequestParam("username") String memberName,
@RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName, memberAge);
return "ok";
}
/**
* @RequestParam 사용
* HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParam(name="xx") 생략 가능
*/
@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(
@RequestParam String username,
@RequestParam int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
/**
* @RequestParam 사용
* String, int 등의 단순 타입이면 @RequestParam도 생략 가능
*/
@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
/**
* @RequestParam.required
* /request-param -> 이 경우 username이 없으므로 예외
*/
@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
@RequestParam(required = true) String username, // 필수 파라미터
@RequestParam(required = false) Integer age) { // null값 때문에 Integer를 사용해야 한다.
log.info("username={}, age={}", username, age);
return "ok";
}
/**
* @RequestParam.required
* 기본값이 지정된 경우 required는 빼도 됨.
*/
@ResponseBody
@RequestMapping("/request-param-default")
public String requestParamDefault(
@RequestParam(required = true, defaultValue = "guest") String username,
@RequestParam(required = false, defaultValue = "-1") Integer 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
위 방법으로 개발 시, 파라미터가 많아지면 번거로운 과정이 생길 수 있다.
실제 개발에선 요청 파라미터를 받아 필요한 객체를 만들고, 그 객체에 값을 넣어주어야 한다. 스프링은 이 과정을 모두 자동화해주는 기능을 제공하는데 이것이 바로 @ModelAttribute
이다.
요청 파라미터를 바인딩 받을 객체는 다음과 같다.
@Data
public class HelloData {
private String username;
private int age;
}
@Slf4j
@Controller
public class RequestParamController {
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
}
스프링 MVC는 @ModelAttribute
가 있으면 다음을 실행한다.
HelloData
객체 생성HelloData
객체의 프로퍼티를 찾고 해당 프로퍼티의 setter를 호출해서 파라미터의 값을 입력(바인딩)한다.BindException
이 발생한다.@ModelAttribute
역시 생략이 가능하다. @RequestParam
까지 생략한다면 다음 규칙을 적용한다.
@RequestParam
: String, int, Integer 같은 단순 타입@ModelAttribute
: 나머지 (argument resolver로 지정해둔 타입은 제외)