✅ @Controller ✅ @RestController ✅ RequestMapping ✅ @RequestParam ✅ @ModelAttribute
@RestController
public class MappingController {
private Logger log = LoggerFactory.getLogger(getClass());
@RequestMapping("/hello-basic")
public String helloBasic(){
log.info("helloBasic");
return "ok";
}
}
@Controller 는 반환 값이 String 이면 뷰 이름으로 인식된다. 그래서 뷰를 찾고 뷰가 랜더링 된다.
@Conroller 의 사용 가능한 파라미터 목록
@Conroller 의 사용 가능한 응답 값 목록
@RestController 는 반환 값으로 뷰를 찾는 것이 아니라, HTTP 메시지 바디에 바로 입력한다.
따라서 실행 결과로 ok 메세지를 받을 수 있다.
" " URL 호출이 오면 이 메서드가 실행되도록 매핑한다.
@GetMapping(value = "/mapping-get-v2")
public String mappingGetV2() {
log.info("mapping-get-v2");
return "ok";
}
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
log.info("mappingPath userId={}", data);
return "ok";
}
만약 어떤 resource를 식별하고 싶으면 Path Variable을 사용하고,
정렬이나 필터링을 한다면 Query Parameter를 사용하는 것이 Best Practice이다.
@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";
}
}
/url?username=hello&age=20
content-type: application/x-www-form-urlencoded
HTTP message body에 데이터를 직접 담아서 요청
@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");
}
<!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>
@ResponseBody // View 조회를 무시하고, HTTP message body에 직접 해당 내용 입력 👉 RessController와 같은 효과
@RequestMapping("/request-param-v2")
public String requestParamV2(
@RequestParam("username") String memberName,
@RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName, memberAge);
return "ok";
}
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";
}
String
,int
,Integer
등의 단순 타입이면 @RequestParam 도 생략 가능
@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, 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";
}
👉 파라미터 이름만 있고 값이 없는 경우 빈문자로 통과
👉 null 을 int 에 입력하는 것은 불가능(500 예외 발생)
👉 따라서 null 을 받을 수 있는 Integer 로 변경하거나, defaultValue
옵션을 사용해야 함
요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 값을 넣어주는 과정을 완전히 자동화해주는 기능
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@RequestParam
: String , int , Integer 같은 단순 타입@ModelAttribute
: 나머지 (HttpServletRequest 같이 argument resolver 로 지정해둔 타입 외)@ModelAttribute
@RequestBody
👉 json에 담기는 속성들로만 이루어져 있다면 @RequestBody
사용하면 되고,
json에 담기지 않는 이미지 파일 같은 MultipartFile을 dto에 같이 사용해야 한다면 @ModelAttribute
을 사용한다.
@NoArgsConstructor
@AllArgsConstructor
@Data
public class createBoardReq {
private String title;
private String content;
private List<MultipartFile> photos;
private Long userId;
private CategoryName categoryName1;
private CategoryName categoryName2;
private CategoryName categoryName3;
public Board toEntityBoard(User user) {
return new Board(user, this.title, this.content, LocalDateTime.now());
}
public Category toEntityCategory(CategoryName categoryName){
return Category.builder()
.categoryName(categoryName)
.build();
}
}
/**
* 게시글 등록
* @author 강신현
*/
@ApiOperation(value = "게시글 등록", notes = "swagger에서 이미지 여러장 업로드 시, 에러가 있으므로 postman에서 테스트 해주세요 (https://www.postman.com/solar-desert-882435/workspace/plogging/request/18177198-883b3d8e-82a7-4228-8bb6-c076ad75749a)")
@PostMapping("")
public ApplicationResponse<BoardRes> boardCreate(@ModelAttribute createBoardReq createBoardReq){
return boardService.createBoard(createBoardReq);
}