복붙노트

[SPRING] @RequestBody와 @RequestParam의 차이점은 무엇입니까?

SPRING

@RequestBody와 @RequestParam의 차이점은 무엇입니까?

@RequestBody에 대해 알기 위해 Spring 설명서를 읽었으며 다음 설명을 제공했습니다.

@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
  writer.write(body);
}

하지만 내 혼란은 그들이 문서에 쓴 문장입니다.

그것들이 의미하는 것은 무엇입니까? 아무도 나에게 모범을 보여줄 수 있습니까?

Spring doc의 @RequestParam 정의는 다음과 같습니다.

나는 그들 사이에 혼란스러워졌다. 그들이 어떻게 다른지에 대한 예를 들어 도와주세요.

해결법

  1. ==============================

    1.@RequestParam 주석 매개 변수는 특정 Servlet 요청 매개 변수에 연결됩니다. 매개 변수 값은 선언 된 메소드 인수 유형으로 변환됩니다. 이 주석은 메서드 매개 변수가 웹 요청 매개 변수에 바인딩되어야 함을 나타냅니다.

    @RequestParam 주석 매개 변수는 특정 Servlet 요청 매개 변수에 연결됩니다. 매개 변수 값은 선언 된 메소드 인수 유형으로 변환됩니다. 이 주석은 메서드 매개 변수가 웹 요청 매개 변수에 바인딩되어야 함을 나타냅니다.

    예를 들어 Spring RequestParam에 대한 Angular 요청은 다음과 같이 보일 것입니다 :

    $http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
          .success(function (data, status, headers, config) {
                            ...
                        })
    

    RequestParam의 끝점 :

    @RequestMapping(method = RequestMethod.POST, value = "/register")
    public Map<String, String> register(Model uiModel,
                                        @RequestParam String username,
                                        @RequestParam String password,
                                        @RequestParam boolean auth,
                                        HttpServletRequest httpServletRequest) {...
    

    @RequestBody 주석 매개 변수는 HTTP 요청 본문에 연결됩니다. 매개 변수 값은 HttpMessageConverters를 사용하여 선언 된 메서드 인수 형식으로 변환됩니다. 이 주석은 메서드 매개 변수가 웹 요청의 본문에 바인딩되어야 함을 나타냅니다.

    예를 들어 Spring RequestBody에 대한 Angular 요청은 다음과 같습니다.

    $scope.user = {
                username: "foo",
                auth: true,
                password: "bar"
            };    
    $http.post('http://localhost:7777/scan/l/register', $scope.user).
                            success(function (data, status, headers, config) {
                                ...
                            })
    

    RequestBody가있는 끝점 :

    @RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                    value = "/register")
    public Map<String, String> register(Model uiModel,
                                        @RequestBody User user,
                                        HttpServletRequest httpServletRequest) {... 
    

    희망이 도움이됩니다.

  2. ==============================

    2.@RequestParam annotation은 요청 매개 변수를 GET / POST 요청에서 메소드 인수로 매핑해야한다는 것을 Spring에 알린다. 예 :

    @RequestParam annotation은 요청 매개 변수를 GET / POST 요청에서 메소드 인수로 매핑해야한다는 것을 Spring에 알린다. 예 :

    의뢰:

    GET: http://someserver.org/path?name=John&surname=Smith
    

    엔드 포인트 코드 :

    public User getUser(@RequestParam(value = "name") String name, 
                        @RequestParam(value = "surname") String surname){ 
        ...  
        }
    

    그래서 기본적으로 @RequestBody는 전체 사용자 요청 (POST의 경우에도)을 String 변수로 매핑하지만 @RequestParam은 메소드 인수에 대해 하나 이상의 매개 변수를 요구합니다.

  3. ==============================

    3.@RequestParam은 요청 매개 변수를 GET / POST 요청에서 메소드 인수로 매핑하도록 Spring을 만듭니다.

    @RequestParam은 요청 매개 변수를 GET / POST 요청에서 메소드 인수로 매핑하도록 Spring을 만듭니다.

    GET 요청

    http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia
    
    public String getCountryFactors(@RequestParam(value = "city") String city, 
                        @RequestParam(value = "country") String country){ }
    

    POST 요청

    @RequestBody는 전체 요청을 모델 클래스에 매핑하도록 Spring을 만듭니다. 거기에서 getter 및 setter 메소드에서 값을 검색하거나 설정할 수 있습니다. 아래를 확인하십시오.

    http://testwebaddress.com/getInformation.do
    

    프런트 엔드에서 JSON 데이터를 가져 와서 컨트롤러 클래스에 충돌합니다.

    {
       "city": "Sydney",
       "country": "Australia"
    }
    

    Java 코드 - 백엔드 (@RequestBody)

    public String getCountryFactors(@RequestBody Country countryFacts)
        {
            countryFacts.getCity();
            countryFacts.getCountry();
        }
    
    
    public class Country {
    
        private String city;
        private String country;
    
        public String getCity() {
            return city;
        }
    
        public void setCity(String city) {
            this.city = city;
        }
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    }
    
  4. ==============================

    4.다음은 @RequestBody의 예입니다. 컨트롤러를 먼저 살펴 봅니다 !!

    다음은 @RequestBody의 예입니다. 컨트롤러를 먼저 살펴 봅니다 !!

      public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {
    
       ...
            productService.registerProductDto(newProductDto);
            return new ResponseEntity<>(HttpStatus.CREATED);
       ....
    
    }
    

    여기에는 각도 조절기가 있습니다.

    function postNewProductDto() {
                    var url = "/admin/products/newItem";
                    $http.post(url, vm.newProductDto).then(function () {
                                //other things go here...
                                vm.newProductMessage = "Product successful registered";
                            }
                            ,
                            function (errResponse) {
                                //handling errors ....
                            }
                    );
                }
    

    그리고 양식에 대한 짧은 견해

     <label>Name: </label>
     <input ng-model="vm.newProductDto.name" />
    
    <label>Price </label> 
     <input ng-model="vm.newProductDto.price"/>
    
     <label>Quantity </label>
      <input ng-model="vm.newProductDto.quantity"/>
    
     <label>Image </label>
     <input ng-model="vm.newProductDto.photo"/>
    
     <Button ng-click="vm.postNewProductDto()" >Insert Item</Button>
    
     <label > {{vm.newProductMessage}} </label>
    
  5. from https://stackoverflow.com/questions/28039709/what-is-difference-between-requestbody-and-requestparam by cc-by-sa and MIT license