Spring에게 해당 Class가 Controller의 역할을 한다고 명시하기 위해 사용하는 Annotation
@Controller // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user") // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUser(Model model) {
// GET method, /user 요청을 처리
}
}
서버에 GET 방식으로 HTTP Request를 보낼 때 URL 주소에 데이터를 추가해서 전송하는 방법
GET http://localhost:8080/request/star/Robbie/age/95
데이터 : /star/Robbie/age/95
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
?
와 &
를 추가하여 사용GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
데이터 : ?name=Robbie&age=95
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
POST http://localhost:8080/hello/request/form/param
Header : Content type: application/x-www-form-urlencoded
Body : name=Robbie&age=95
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
@RequestParam
은 생략 가능@RequestParam(required = false)
@RequestBody
가 JSON을 받는 것과 달리 @ModenAttribute
의 경우에는 json을 받아 처리할 수 없다.POST http://localhost:8080/hello/request/form/model
Header : Content type: application/x-www-form-urlencoded
Body : name=Robbie&age=95
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
POST http://localhost:8080/hello/request/form/json
Header : Content type: application/json
Body : {"name":"Robbie","age":"95"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
= @Controller
+ @RequestBody
@RestController
를 사용하면 해당 클래스의 모든 메서드에 @ResponseBody
애너테이션이 추가되는 효과를 부여할 수 있다.
@RequestBody
: 이 애너테이션이 붙은 파라미터에는 http요청의 본문(body)이 그대로 전달된다.
→ 일반적인 GET/POST의 요청 파라미터라면 @RequestBody
를 사용할 일이 없지만, xml이나 JSON기반의 메시지를 사용하는 요청의 경우 이 방법이 매우 유용
개발자가 생성한 Class를 Spring의 Bean으로 등록할 때 사용
@Component(value="myman")
public class Man {
public Man() {
System.out.println("hi");
}
}
@ComponentScan
Annotation이 있는 클래스의 하위 Bean을 등록 될 클래스들을 스캔하여 Bean으로 등록
개발자가 제어가 불가능한 외부 라이브러리와 같은 것들을 Bean으로 만들 때 사용
Request의 header값을 가져올 수 있으며, 해당 Annotation을 쓴 메소드의 파라미터에 사용
@Controller // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user") // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUser(@RequestHeader(value="Accept-Language") String acceptLanguage) {
// GET method, /user 요청을 처리
}
}
호출하는 클라이언트의 정보를 가져다가 서버(controller)에 전달해주는 매핑
RequestMapping(Method=RequestMethod.GET)과 똑같은 역할
@Controller // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user") // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
@GetMapping("/")
public String getUser(Model model) {
// GET method, /user 요청을 처리
}
////////////////////////////////////
// 위와 아래 메소드는 동일하게 동작합니다. //
////////////////////////////////////
@RequestMapping(method = RequestMethod.GET)
public String getUser(Model model) {
// GET method, /user 요청을 처리
}
}
RequestMapping(Method=RequestMethod.POST)과 똑같은 역할
@Controller // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user") // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
@RequestMapping(method = RequestMethod.POST)
public String addUser(Model model) {
// POST method, /user 요청을 처리
}
////////////////////////////////////
// 위와 아래 메소드는 동일하게 동작합니다. //
////////////////////////////////////
@PostMapping('/')
public String addUser(Model model) {
// POST method, /user 요청을 처리
}
}
Bean을 주입받기 위하여 @Autowired 를 사용
Spring Boot Test에 필요한 의존성을 제공
// DemoApplicationTests.java
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}
JUnit에서 테스트 할 대상을 표시
@NonNull
: 자동으로 null체크를 진행하고 null인 경우 NullPointException
을 발생
@Getter
: Class 모든 필드의 Getter method를 생성
@Setter
: Class 모든 필드의 Setter method를 생성
@NoArgsConstructor
: Class 기본 생성자를 자동으로 추가
@AllArgsConstructor
: Class 모든 필드 값을 파라미터로 받는 생성자를 추가
@RequiredArgsConstructor
: final이나'@NonNull'이 있는 필드가 포함된 생성자를 자동 생성
@ToString
: Class 모든 필드의 toString method를 생성
@CleanUp
: 자동으로 자원관리, close()메서드를 호출하여 자원 종류@EqualsAndHashCode
: hashCode, equals 구현@Builder
: 해당 클래스에 빌드 패턴을 적용한 클래스를 생성