Web/spring

[Annotation] Spring Web Annotations

태애니 2023. 3. 31. 20:19
728x90

https://www.baeldung.com/spring-mvc-annotation

 

 

 


 

 

 

 

org.springframework.web.bind.annotation package.

 

 

 

 

@RequestMapping

request handler methods inside @Controller classes

  • path, or its aliases, name, and value: which URL the method is mapped to 
  • method: compatible HTTP methods
  • params: filters requests based on presence, absence, or value of HTTP parameters
  • headers: filters requests based on presence, absence, or value of HTTP headers
  • consumes: which media types the method can consume in the HTTP request body
  • produces: which media types the method can produce in the HTTP response body
@Controller
class VehicleController {

    @RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)
    String home() {
        return "home";
    }
}

 

 

Class 수준에서 사용하면 @Controller 클래스의 모든 핸들러 method에 대한 기본 설정이 가능함

@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
class VehicleController {

    @RequestMapping("/home")
    String home() {
        return "home";
    }
}

 

 

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping are different variants of @RequestMapping with the HTTP method already set to GET, POST, PUT, DELETE, and PATCH respectively.

 

 

 

 

@RequestBody

HTTP에서 request하는 객체를 매핑함

@PostMapping("/save")
void saveVehicle(@RequestBody Vehicle vehicle) {
    // ...
}

 

나는 주로 @RequestBody 매핑을 DTO로 만들어 데이터를 주고 받는다

그럼 validation 적용도 간단하다

 

The deserialization is automatic and depends on the content type of the request.

 

 

@PathVariable

이 애노테이션은 메서드 인수가 URI 템플릿 변수에 바인딩되어 있음 을 나타낸다

url/{id=인수1}/sample/{인수2} << 이런 부분에 접근이 가능하도록

이 애노테이션을 사용하여 URI 템플릿을 지정해주고 @PathVariable을 사용하여 템플릿 부분 중 하나에 메서드 인수를 바인딩도 가능하다.

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable("id") long id) {
    // ...
}

If the name of the part in the template matches the name of the method argument, we don't have to specify it in the annotation:

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable long id) {
    // ...
}

 

필수 인수를 false로 하면 값이 없을 수도 있음을 나타낸다

Moreover, we can mark a path variable optional by setting the argument required to false:

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable(required = false) long id) {
    // ...
}

 

 

 

@RequestParam

쉽게말해서 url?key=value << 이부분에 접근할 때 사용한다

 

HTTP 요청 매개변수에 액세스하기 위해 @RequestParam을 사용

 

 

@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
    // ...
}

 

@PathVariable 애노테이션과 동일한 구성 옵션이 있고,

@RequestParam을 사용하면 Spring이 요청에서 값이 없거나 비어 있는 경우 주입된 값을 지정해줄 수 있다 defaultValue를 설정하면 된다

기본값으로 제공하면 required=false 로 설정된다

 

@RequestMapping("/buy")
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
    // ...
}

 

 

 

매개변수 외에도 액세스할 수 있는 다른 HTTP 요청 부분인 쿠키 및 헤더가 있다.

@CookieValue  @RequestHeader 주석으로 액세스할 수 있다 .

@RequestParam 과 같은 방식으로 설정할 수 있다 .

 

 


Response Handling Annotations

 

@ResponseBody

Spring treats the result of the method as the response itself

method 의 결과를 응답 자체로 처리해준다

@ResponseBody
@RequestMapping("/hello")
String hello() {
    return "Hello World!";
}

@Controller 클래스 에 주석을 달면 모든 요청 처리기 메서드가 이를 사용한다

 

 

 

@ExceptionHandler

we can declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions.

사용자가 직접 지정 오류 handler method로 처리해준다

@ExceptionHandler(IllegalArgumentException.class)
void onIllegalArgumentException(IllegalArgumentException exception) {
    // ...
}

 

 

 

@ResponseStatus

 desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument.

Also, we can provide a reason using the reason argument.

We also can use it along with @ExceptionHandler

 

쉽게말해 HttpStatus 응답상태를 지정해줄 수 있음

@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
void onIllegalArgumentException(IllegalArgumentException exception) {
    // ...
}

https://www.baeldung.com/spring-mvc-controller-custom-http-status-code

 

 

 

 

Other Web Annotations

Some annotations don't manage HTTP requests or responses directly.

 

 

@Controller

@Controller 로 Spring MVC 컨트롤러를 정의할 수 있다.

https://www.baeldung.com/spring-bean-annotations

 

 

 

@RestController

= @Controller + @ResponseBody 

 

@Controller
@ResponseBody
class VehicleRestController {
    // ...
}

// 아래와 동일
@RestController
class VehicleRestController {
    // ...
}

 

 

@ModelAttribute

access elements that are already in the model of an MVC @Controller, by providing the model key

model 키를 제공하여 요소들에 액세스 가능하다

thymeleaf 사용할 때 매우 유용하다

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) {
    // ...
}

Like with @PathVariable and @RequestParam, we don't have to specify the model key if the argument has the same name:

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute Vehicle vehicle) {
    // ...
}

 

 

Besides, @ModelAttribute has another use: if we annotate a method with it, Spring will automatically add the method's return value to the model:

@ModelAttribute("vehicle")
Vehicle getVehicle() {
    // ...
}

 

 

Like before, we don't have to specify the model key, Spring uses the method's name by default:

@ModelAttribute
Vehicle vehicle() {
    // ...
}

Before Spring calls a request handler method, it invokes all @ModelAttribute annotated methods in the class.

More information about @ModelAttribute can be found in this article.

 

 

 

 

 

 

 

@CrossOrigin

@CrossOrigin enables cross-domain communication for the annotated request handler methods:

@CrossOrigin
@RequestMapping("/hello")
String hello() {
    return "Hello World!";
}Copy

If we mark a class with it, it applies to all request handler methods in it.

We can fine-tune CORS behavior with this annotation's arguments.

For more details, please visit this article.

 

 

 

 

728x90