@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
@RequestMapping("/hello-basic")
public String helloBasic() {
log.info("helloBasic");
return "ok";
}
}
Get,Head,Post,Put,Patch,Delte
@RestController
@Controller
는 반환 값이 String
이면 뷰 이름으로 인식된다. 그 결과 뷰를 찾고 뷰가 렌더링 된다.@RestController
는 반환 값으로 뷰를 찾는 것이 아니라 Http
메시지 바디에 바로 입력한다.@RequestMapping("/hello-basic)
hello-basic
URL 호출이 오면 이 메서드가 실행되도록 매핑한다.배열[]
로 제공하므로 다중 설정이 가능하다. {"hello-basic","/hello-go"}
@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
@GetMapping(value="/mapping-get-v1")
위의 코드는 모두 동일한 것이다.
PathVariable(경로변수 사용)
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
이 경로는 리소스 경로에 식별자를 넣는 스타일이다.
@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";
}
@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)){
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";
}
}
HttpServletRequest
HttpServletResponse
HttpMethod:
HTTP 메서드를 조회한다Locale:
Locale 정보를 조회한다@RequestHeader("host") String host
@CookieValue(value="myCookie",required=false)String cookie
MutivalueMap
Get 쿼리 파라미터 전송 예시
http://localhost:8080/request-param?username=hello&age=20
Post,HTML Form 전송
POST /request-param ...
content-type: application/x-www-form-urlencoded
username=hello&age=20
@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");
}
request.getParameter()
여기서는 단순히 HttpServletRequest가 제공하는 방식으로 요청 파라미터를 조회했다.
@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:
파라미터 이름으로 바인딩@ResponseBody:
View 조회를 무시하고 Http message body에 직접 해당 내용 입력@RequestParam String username
: Http 파라미터 이름이 변수와 같으면 name값을 생략 할 수 있다String username:
String,int,Integer
등의 단순 타입이면 @RequestParam
도 생략이 가능하다 @RequestParam(required = true) String username
@RequestParam(required = false) Integer age
@RequestParam.required
/request-param-required?username=
값이 null
이 들어와서 오류가 발생한다required=false
로 변경시 username
값이 null로 들어와도 오류가 발생하지 않는다null
값이 들어갈 수 없다@RequestParam(required = false) int age
경우에는 null
이 들어갈 수 없으므로 Integer
값으로 변경해야한다defaultValue
defaultValue
에 값을 지정하면 기본 값을 적용할 수 있다@RequestParam Map<String,Object> paramMap
paramMap.get("age"))
로 값을 얻을 수 있다Map
을 사용해도 되지만 그렇지 않다면 MultiValueMap
을 사용하자
@Data
public class HelloData {
private String username;
private int age;
}
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(),
helloData.getAge());
return "ok";
}
@ModelAttribute
가 있으면HelloData
객체를 생성한다HelloData
객체의 프로퍼티를 찾는다. 그리고 해당 프로퍼티의 setter를 호출해서 파라미터의 값을 바인딩한다@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");
}
InputStream(Reader):
HTTP 요청 메시지 바디의 내용을 직접 조회OutputStream(Writer):
HTTP 응답 메시지의 바디에 직접 결과 출력 @PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
String messageBody = httpEntity.getBody();
log.info("messageBody={}", messageBody);
return new HttpEntity<>("ok");
}
HttpEntity: HTTP header,body 정보를 편리하게 조회
HttpEnttiy는 응답에도 사용 가능
HttpEntity
를 상속받은 다음 객체들도 같은 기능을 제공한다
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED)
@Controller
public class RequestBodyJsonController {
private ObjectMapper objectMapper = new ObjectMapper();
@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 data = objectMapper.readValue(messageBody, HelloData.class);
log.info("username={}, age={}", data.getUsername(), data.getAge());
response.getWriter().write("ok");
}
}
objectMapper
를 사용해서 자바 객체로 변환한다@RequestBody String messageBody
HelloData data = objectMapper.readValue(messageBody, HelloData.class);
@RequestBody
를 사용해서 HTTP 메시지에서 데이터를 꺼내고 messageBody에 저장한다messageBody
를 objectMapper
를 통해서 자바 객체로 변환한다 @ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(@RequestBody HelloData data) {
log.info("username={}, age={}", data.getUsername(), data.getAge());
return "ok";
}
HttpEntity,@RequestBody
를 사용하면 HTTP 메시지 컨버터가 HTTP 메시지 바디의 내용을 우리가 원하는 문자나 객체로 변환해준다.@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) {
HelloData data = httpEntity.getBody();
log.info("username={}, age={}", data.getUsername(), data.getAge());
return "ok";
}
HttpEntity
를 활용할 수 있다 @GetMapping("/response-body-string-v2")
public ResponseEntity<String> responseBodyV2() {
return new ResponseEntity<>("ok", HttpStatus.OK);
}
@GetMapping("/response-body-json-v1")
public ResponseEntity<HelloData> responseBodyJsonV1() {
HelloData helloData = new HelloData();
helloData.setUsername("userA");
helloData.setAge(20);
return new ResponseEntity<>(helloData, HttpStatus.OK);
}
ResponseEntity
로 메시지 바디에 직접 글을 쓸수 있다@ResponseBody
로 Http 메시지 컨버터로 전달하는 방식도 가능하다
출처: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard