스프링 MVC에 대해서 복습할 겸 해서 정리를 해 테스트 해보았다. 따로 뷰 템플릿을 사용하는 경우는 제외하고 REST API로 응답을 하는 경우만 테스트했다.
요청
쿼리 파라미터
@GetMapping("/qTest1")
public String qTest1(@RequestParam(value = "name") String n, @RequestParam(value = "age") int a) {
log.info("name={}, age={}", n, a);
return "test";
}
ㄴ @RequestParam 어노테이션 사용 / value를 지정하여 파라미터 변수명과 달라도 됨
@GetMapping("/qTest2")
public String qTest2(@RequestParam String name, @RequestParam int age) {
log.info("name={}, age={}", name, age);
return "test";
}
ㄴ @RequestParam 어노테이션 사용 / value를 지정하지 않아서 파라미터 변수명이 쿼리 파라미터로 전달되는 이름과 같아야 함
@GetMapping("/qTest3")
public String qTest3(String name, int age) { // @RequestParam 생략
log.info("name={}, age={}", name, age);
return "test";
}
ㄴ 직접 정의한 클래스를 자료형으로 사용하지 않는 경우는 @RequestParam 생략 가능
@GetMapping("/qTest4")
public String qTest4(HttpServletRequest request) {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
log.info("name={}, age={}", name, age);
return "test";
}
ㄴ HttpServletRequest.getParameter()를 이용하여 직접 데이터를 꺼낼 수 있다.
@GetMapping("/qTest5")
public String qTest5(@RequestParam Map<String, String> paramMap) {
String name = paramMap.get("name");
int age = Integer.parseInt(paramMap.get("age"));
log.info("name={}, age={}", name, age);
return "test";
}
ㄴ Map을 이용하여 parameter의 Map을 사용할 수 있다. 이 때도 @RequestParam 어노테이션을 붙여주어야 한다.
POST Form
기본적으로 쿼리 파라미터를 이용한 방식과 동일하게 사용할 수 있다. 어노테이션만 @PostMapping으로 변경해주면 된다.
HTTP Body
@Data
public class Student {
private String name;
private int age;
}
ㄴ Student 클래스
@PostMapping("/hTest1")
public String hTest1(HttpServletRequest request) throws IOException {
Student student = new ObjectMapper().readValue(request.getInputStream(), Student.class);
log.info("name={}, age={}", student.getName(), student.getAge());
return "test";
}
ㄴ HttpServletRequest.getInputStream()으로 SetvletInputStream을 가져와 ObjectMapper로 미리 만들어둔 Student 클래스로 매핑한다.
@PostMapping("/hTest2")
public String hTest2(InputStream body) throws IOException {
Student student = new ObjectMapper().readValue(body, Student.class);
log.info("name={}, age={}", student.getName(), student.getAge());
return "test";
}
ㄴ InputStream을 직접 파라미터로 받을 수 있다.
@PostMapping("/hTest3")
public String hTest3(@RequestBody Student student) {
log.info("name={}, age={}", student.getName(), student.getAge());
return "test";
}
ㄴ @RequestBody 어노테이션을 이용하여 직접 Student 클래스를 지정하여 사용할 수 있다.
응답
@PostMapping("/rTest1")
public void rTest1(@RequestBody Student student, HttpServletResponse response) throws IOException {
log.info("name={}, age={}", student.getName(), student.getAge());
response.getWriter().write("test");
}
ㄴ 리턴값을 설정하지 않고, HttpServletResponse.getwriter()를 이용하여 직접 HTTP 응답 메시지 body에 String을 작성할 수 있다.
@ResponseBody
@PostMapping("/rTest2")
public String rTest2(@RequestBody Student student) {
log.info("name={}, age={}", student.getName(), student.getAge());
return "test";
}
ㄴ @ResponseBody 어노테이션을 사용하여 String을 리턴함으로써 HTTP 응답 메시지 body에 String을 작성한다.
@ResponseBody
@PostMapping("/rTest3")
public Student rTest3(@RequestBody Student student) { // 직접 정의한 객체 리턴 가능
log.info("name={}, age={}", student.getName(), student.getAge());
return student;
}
ㄴ 직접 정의한 Student 클래스를 반환함으로써 HTTP 응답 메시지 body에 JSON 형태로 Student 데이터를 작성한다.
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PostMapping("/rTest4")
public String rTest4(@RequestBody Student student) {
log.info("name={}, age={}", student.getName(), student.getAge());
return "test";
}
ㄴ @ResponseBody로 String을 반환하면서 상태코드를 @ResponseStatus 어노테이션을 통해 지정할 수 있다. (반환 타입이 String이 아니어도 가능)
@PostMapping("/rTest5")
public ResponseEntity<String> rTest5(@RequestBody Student student) {
log.info("name={}, age={}", student.getName(), student.getAge());
return new ResponseEntity<>("test", HttpStatus.OK);
}
ㄴ 스프링에서 제공하는 ResponseEntity 객체를 이용하여 body의 내용과 상태코드를 포함시켜 리턴할 수 있다.
@PostMapping("/rTest6")
public ResponseEntity<Student> rTest6(@RequestBody Student student) {
log.info("name={}, age={}", student.getName(), student.getAge());
return ResponseEntity.ok(student);
}
ㄴ 이런식으로 클래스 메서드를 이용하여 짧게 작성할 수도 있다.