복붙노트

[SPRING] 스프링의 @RequestBody 및 @RequestParam 학습

SPRING

스프링의 @RequestBody 및 @RequestParam 학습

Spring을 사용하는 웹 프로젝트를 편집 중이고 일부 Spring의 주석을 추가해야합니다. 내가 추가하는 두 가지는 @RequestBody와 @RequestParam입니다. 나는 조금 주위를 파고 들었지만 이것을 발견했지만 이러한 주석을 사용하는 방법을 완전히 이해하지 못하고 있습니다. 누구든지 예제를 제공 할 수 있습니까?

해결법

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

    1.컨트롤러 예제 :

    컨트롤러 예제 :

    @Controller
    class FooController {
        @RequestMapping("...")
        void bar(@RequestBody String body, @RequestParam("baz") baz) {
            //method body
        }
    }
    

    @RequestBody : 변수 본문에 HTTP 요청의 본문이 포함됩니다.

    @RequestParam : 변수 baz는 요청 매개 변수 baz의 값을 보유합니다.

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

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

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

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

    $http.post('http://localhost:7777/scan/l/register', {params: {"username": $scope.username, "password": $scope.password, "auth": true}}).
                        success(function (data, status, headers, config) {
                            ...
                        })
    
    @RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
    public Map<String, String> register(Model uiModel,
                                        @RequestParam String username, @RequestParam String password, 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) {
                                ...
                            })
    
    @RequestMapping(method = RequestMethod.POST, produces = "application/json", value = "/register")
    public Map<String, String> register(Model uiModel,
                                        @RequestBody User user,
                                        HttpServletRequest httpServletRequest) {...
    

    희망이 도움이됩니다.

  3. from https://stackoverflow.com/questions/3337350/learning-springs-requestbody-and-requestparam by cc-by-sa and MIT license