기본적인 요청은 다음과 같이 매핑할 수 있다.
@RestController
public class MappingController {
@RequestMapping(value = "/hello-basic",method = RequestMethod.GET)
public String helloBasic() {
log.info("helloBasic");
return "ok";
}
}
@RestController
는 반환 값으로 뷰를 찾는 것이 아니라 HTTP 메시지 바디에 바로 입력한다.@Controller
는 반환값이 String이면 뷰 이름으로 인식하고 뷰를 찾아 랜더링한다.@RequestMapping
의 value에 해당하는 url의 요청이 오면 해당 메소드를 실행한다. @GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
@RequestMapping
은 URL 경로를 템플릿화 할 수 있다.@PathVariable
을 사용하면 매칭되는 부분을 파라미터로 받을 수 있다.@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
@PostMapping(value = "/mapping-consume", consumes = MediaType.APPLICATION_JSON_VALUE)
Http 요청의 Content-Type이 일치하는 경우만 매핑 가능
@PostMapping(value = "/mapping-produce", produces = MediaType.TEXT_HTML_VALUE)
Http 요청의 Accept 타입이 일치하는 경우만 매핑 가능
애노테이션 기반의 스프링 컨트롤러는 다양한 파라미터를 지원한다.
@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) {
//...
}
HttpServletRequest
HttpServletResponse
HttpMethod
: HTTP 메서드를 조회Locale
: Locale 정보 조회@RequestHeader MultiValue<String, String> headerMap
: 모든 헤더를 MultiValueMap 형식으로 조회@RequestHeader("host") String host
required
: 필수 값 여부 defaultValue
: 기본 값@CookieValue(value = "myCookie", required = false) String cookie
required
: 필수 값 여부 defaultValue
: 기본 값클라이언트에서 서버로 요청 데이터를 전달할 때 다음 3가지 방법을 사용한다.
Get- 쿼리파라미터와 Post - HTML Form 의 데이터는 같은 형식의 데이터이므로 구분 없이 조회할 수 있다. 이를 요청 파라미터(request parameter) 조회라고 한다.
@RequestMapping("/request-param")
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");
}
파라미터로 HttpServletRequest를 받아서 getParameter
를 사용하여 파라미터를 조회할 수 있다.
@ResponseBody
@RequestMapping("/request-param")
public String requestParamV3(@RequestParam String username, @RequestParam int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
@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";
}
@RequestParam을 사용하고 파라미터 타입을 Map으로 지정하면 모든 파라미터를 맵의 Key, Value로 받을 수 있다.
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
log.info("helloData={}", helloData);
return "ok";
}
@ModelAttribute
를 사용한HelloData
객체 를 생성한다.@ModelAttribute
는 생략할 수 있다.@RequestParam
적용@ModelAttribute
적용 (argument relsover로 지정한 타입 제외)Property
객체에
setUsername()
,getUsername()
메서드가 있으면 객체는username
이라는 프로퍼티를 가진다고 할 수 있다.
요청 파라미터와 다르게 HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우 @RequestParam
, @ModelAttribute
를 사용할 수 없다.
@PostMapping("/request-body-string-v1")
public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
log.info("messageBody={}", messageBody);
response.getWriter().write("ok");
}
@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
log.info("messageBody={}", messageBody);
responseWriter.write("ok");
}
스프링 MVC는 다음 파라미터를 지원한다.
@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {
String messageBody = httpEntity.getBody();
log.info("messageBody={}", messageBody);
return new HttpEntity<>("ok");
}
HttpEntity
: Http header, body 정보를 편리하게 조회
요청 파라미터를 조회하는 @RequestParam
, @ModelAttribute
기능과는 관계없음.
HttpEntity
는 응답에도 사용 가능
HttpEntity
를 상속받은 RequestEntity
, ResponseEntity
사용 가능
@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) throws IOException {
log.info("messageBody={}", messageBody);
return "ok";
}
@RequestBody
를 사용하면 HTTP 메시지 바디의 내용을 파라미터로 받을 수 있다.
Header 정보가 필요하면 @RequestHeader
사용
@ResponseBody
를 사용하면 응답 결과를 HTTP 메시지 바디에 직접 담는다. (view를 사용하지 않는다.)
@PostMapping("/request-body-json-v1")
public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
log.info("messageBody={}", messageBody);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
response.getWriter().write("ok");
}
@ResponseBody
@PostMapping("/request-body-json-v2")
public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {
log.info("messageBody={}", messageBody);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(@RequestBody HelloData helloData) throws IOException {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@RequestBody는 생략할 수 없다.
스프링은 @ModelAttribute, @RequestParam 을 생략하는 경우 파라미터에
단순 타입은 @RequestParam, 나머지는 @ModelAttribute 을 적용한다.
@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) throws IOException {
HelloData helloData = httpEntity.getBody();
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData helloData) throws IOException {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return helloData;
}
@ResponseBody 를 사용하고 객체를 직접 리턴하면 HTTP 메시지 컨버터는 객체를 JSON으로 변환하여 응답 메시지 바디에 담는다.
HTTP 요청 시 content-type이 application/json 인 경우에 JSON을 처리하는 HTTP 메시지 컨버터가 실행된다.
서버에서 응답 데이터를 만드는 방법은 다음과 같다.
스프링 부트는 클래스패스의 다음 디렉토리에 있는 정적 리소스를 제공한다.
/static
, /public
, /resources
, /META-INF/resources
src/main/resources
는 리소스를 보관하는 경로이고 이 경로의 하위에 위와 같은 이름의 디렉토리로 정적 리소스를 관리할 수 있다.
정적 리소스 경로: src/main/resources
리소스 파일 위치: src/main/resources/static/basic/hello.html
요청 url: http://localhost:8080/basic/hello.html
뷰 템플릿을 거쳐 HTML이 생성되고 뷰가 응답을 만들어서 전달한다.
스프링 부트는 기본 뷰 템플릿 경로를 제공
뷰 템플릿 경로: src/main/resources/templates
@RequestMapping("/response-view-v1")
public ModelAndView responseViewV1() {
ModelAndView mav = new ModelAndView("response/hello")
.addObject("data","hello!!");
return mav;
}
리턴할 뷰의 이름과 데이터를 ModelAndView에 담아 리턴
@RequestMapping("/response-view-v2")
public String responseViewV2(Model model) {
model.addAttribute("data", "hello!!");
return "response/hello";
}
Model을 파라미터로 받아 데이터를 담고 뷰 이름을 String으로 리턴한다.
- @ResponseBody를 사용하지 않으면 ViewResolver가 실행되어 리턴한 String으로 뷰를 찾아 렌터링한다.
- @ResponseBody를 사용하면 HTTP 메시지 바디에 String 이 입력된다.